Python — Object-Oriented Programming (Classes)

A class defines the behavior (methods) and information (attributes) an object stores. A child class inherits the parent’s attributes and methods automatically.

See OOPFoundations for the language-agnostic principles (encapsulation, inheritance, polymorphism) that Python implements. See PythonOOP-CppOOP for a side-by-side C++ comparison.

Defining a Class

class Dog:
    """Represent a dog."""
 
    def __init__(self, name):       # constructor — called on instantiation
        """Initialize the dog."""
        self.name = name            # instance attribute
 
    def sit(self):
        """Simulate sitting."""
        print(f"{self.name} is sitting.")

self

self is always the first parameter of every method. It refers to the specific instance. Python passes it automatically — you don’t include it in the call: my_dog.sit() not my_dog.sit(my_dog).

Creating an Instance

my_dog = Dog('Peso')
print(f"{my_dog.name} is a great dog!")
my_dog.sit()

Inheritance

A child class gets all parent attributes and methods. super().__init__() calls the parent’s constructor so you don’t duplicate setup logic.

class SARDog(Dog):                  # SARDog inherits from Dog
    """Represent a search-and-rescue dog."""
 
    def __init__(self, name):
        """Initialize the sardog."""
        super().__init__(name)      # run Dog's __init__ first
 
    def search(self):               # new method not in parent
        """Simulate searching."""
        print(f"{self.name} is searching.")
 
my_dog = SARDog('Willie')
my_dog.sit()      # inherited from Dog
my_dog.search()   # defined in SARDog

Python OOP vs C++ OOP

ConceptPythonC++ (see OOPFoundations)
Constructordef __init__(self, ...)ClassName(...) with initializer list
Attributesself.name = valuemember variables with type declarations
Methodsdef method(self):member functions
Inheritanceclass Child(Parent):class Child : public Parent
Parent initsuper().__init__(name): Parent(name) in initializer list
Encapsulationconvention (_private)explicit private: / public:
Polymorphismduck typing — implicitvirtual keyword — explicit
Memorymanaged (GC)manual (stack vs. heap)

Duck typing

In Python, if an object has the right methods it works regardless of its class. C++ requires explicit virtual dispatch. Python polymorphism is simpler to write but less visible in code.

Cross-References

  • OOPFoundations — Alan Kay’s 5 characteristics; encapsulation, composition, inheritance, polymorphism
  • PythonOOP-CppOOP — full side-by-side comparison with C++ code examples
  • PythonFunctions — methods are functions; the only difference is the mandatory self parameter
  • PythonDictionaries — before classes, dicts handle structured data; use a class when nesting gets deep
graph TD
    A[Class] --> B["__init__(self, ...): constructor"]
    A --> C["self.x = value: attribute"]
    A --> D["def method(self): method"]
    A --> E[Inheritance]
    E --> F["class Child(Parent):"]
    E --> G["super().__init__(): inherit parent setup"]
    E --> H[Child adds new methods]
    A --> I["my_obj = MyClass(args): instantiate"]
    I --> J["my_obj.attribute"]
    I --> K["my_obj.method()"]