We're making some improvements. Some features may be temporarily unavailable.
intermediate30 min

Object-Oriented Programming

Classes, objects, inheritance, and encapsulation

What is OOP?

Object-Oriented Programming (OOP) is a way of organizing code by bundling data and behavior into reusable blueprints called classes.

Think of a class like a cookie cutter — it defines the shape, and each cookie you make is an object (an instance of that class).

Why OOP?

  • Organize complex programs into logical pieces
  • Reuse code through inheritance
  • Encapsulate data — keep related variables and functions together

Your First Class

Creating a Class and Objects

Output
Run your code to see output here

Breakdown:

  • class Dog: — defines a new class named Dog
  • __init__(self, name, age) — the constructor, runs when you create an object
  • self — refers to the specific instance being created or used
  • self.name = name — stores the parameter as an instance attribute

Check Your Understanding

What is the purpose of the __init__ method?

Instance Methods

Methods are functions that belong to a class. They always take self as their first parameter:

A BankAccount Class

Output
Run your code to see output here

Inheritance

Classes can inherit from other classes — getting all their methods and attributes for free:

Inheritance Hierarchy

Output
Run your code to see output here
  • Cat and Fish inherit from Animal
  • They override the speak() method with their own version
  • They can add their own unique methods (like purr() and swim())

Check Your Understanding

What happens when a child class defines a method with the same name as the parent class?

Class Variables vs Instance Variables

Class vs Instance Variables

Output
Run your code to see output here
  • Class variables are shared across all instances — change once, affects everyone
  • Instance variables (with self.) are unique to each object

Exercise

Create a `Rectangle` class with a constructor that takes `width` and `height`. Add a method `area()` that returns `width * height`, and a method `perimeter()` that returns `2 * (width + height)`. Create a rectangle with width 5 and height 3, then print its area and perimeter.

Python will load on first run

Key Takeaways

  • A class is a blueprint for creating objects
  • The __init__ method initializes new objects
  • self refers to the current instance
  • Inheritance lets child classes reuse parent code
  • Class variables are shared; instance variables are unique
  • Method overriding lets child classes customize inherited behavior

OOP is the foundation of almost every large Python project. Understanding classes sets you up to read and write professional-grade code!

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...