On this page
  1. Object-Oriented Programming (OOP)
  2. Contents
  3. Classes, Instances & __init__
  4. Encapsulation & Properties (@property)
  5. Inheritance, Polymorphism & Abstract Base Classes
  6. Special (Dunder) Methods

Object-Oriented Programming (OOP)

Prev: Intermediate Python & Software Engineering | Up: Intermediate Python & Software Engineering | Next: Modern Data Modeling
Rel: Python Object, MRO & Initialization Dunder Flow, object, super, property, abc
Ref: docs.python.org — Classes | docs.python.org — Data Model
Tags: #public #python3 #tutorials #software-engineering #oop


Contents


Classes, Instances & __init__

A class defines a blueprint for objects, binding state (attributes) and behavior (methods). Class attributes are shared across all instances; instance attributes are set on self inside __init__.

class BankAccount:
    currency = "USD"  # Class attribute

    def __init__(self, owner: str, balance: float = 0.0) -> None:
        self.owner = owner        # Instance attribute
        self._balance = balance   # Protected-by-convention attribute

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

    @classmethod
    def zero_account(cls, owner: str) -> "BankAccount":
        return cls(owner, 0.0)

    @staticmethod
    def format_money(amount: float) -> str:
        return f"${amount:,.2f}"

For the full lifecycle of how type.__call__, __new__, __init__, and MRO interact during instantiation, see Python Object, MRO & Initialization Dunder Flow.


Encapsulation & Properties (@property)

Python relies on naming conventions (_internal, __name_mangled) and [[__builtins__/property|@property]] descriptors to expose validated attributes without changing call-site syntax.

class Temperature:
    def __init__(self, celsius: float) -> None:
        self.celsius = celsius  # Routes through setter

    @property
    def celsius(self) -> float:
        return self._celsius

    @celsius.setter
    def celsius(self, value: float) -> None:
        if value < -273.15:
            raise ValueError("Below absolute zero")
        self._celsius = float(value)

    @property
    def fahrenheit(self) -> float:
        return self._celsius * 9 / 5 + 32

t = Temperature(25)
print(t.celsius, t.fahrenheit)  # 25.0 77.0

Inheritance, Polymorphism & Abstract Base Classes

Use [[__builtins__/super|super()]] to delegate cooperatively to parent classes, and [[stdlib_module/abc|abc.ABC]] + @abstractmethod to enforce interface contracts.

from abc import ABC, abstractmethod
import math

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        """Return the area of the shape."""

class Circle(Shape):
    def __init__(self, radius: float) -> None:
        self.radius = radius

    def area(self) -> float:
        return math.pi * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, width: float, height: float) -> None:
        self.width = width
        self.height = height

    def area(self) -> float:
        return self.width * self.height

shapes: list[Shape] = [Circle(2), Rectangle(3, 4)]
print([round(s.area(), 2) for s in shapes])  # [12.57, 12]

Special (Dunder) Methods

Double-underscore ("dunder") methods let custom classes integrate seamlessly with built-in operators and protocols (repr, len, +, ==, in, iteration).

class Vector2D:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

    def __repr__(self) -> str:
        return f"Vector2D({self.x!r}, {self.y!r})"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Vector2D):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

    def __add__(self, other: "Vector2D") -> "Vector2D":
        if not isinstance(other, Vector2D):
            return NotImplemented
        return Vector2D(self.x + other.x, self.y + other.y)

    def __abs__(self) -> float:
        return (self.x ** 2 + self.y ** 2) ** 0.5

v = Vector2D(3, 4) + Vector2D(0, 0)
print(repr(v), abs(v))  # Vector2D(3, 4) 5.0

Linked from

Related notes