Skip to content

Object-Oriented Programming in Python: Classes, Inheritance, and Dunder Methods

  • Defining classes, instance attributes, and class attributes.
  • Inheritance, super(), and method overriding.
  • Properties (@property) for controlled attribute access.
  • Dunder (magic) methods for operator overloading and string representation.
  • Practical patterns used in production Python code.

Python is a multi-paradigm language and OOP is one of its three primary styles (alongside procedural and functional). Python’s OOP model is simpler than C#’s or Java’s — there are no access modifiers enforced by the runtime, attributes are added dynamically, and everything is an object including classes and functions.

Save all examples as a .py file and run with python examples.py (Python 3.9+).

class Order:
"""Represents a customer order in OrdersPortal."""
# Class attribute — shared by all instances
tax_rate: float = 0.08
def __init__(self, order_id: str, customer: str, subtotal: float) -> None:
# Instance attributes — unique per object
self.order_id = order_id
self.customer = customer
self.subtotal = subtotal
self.status = "pending"
def total(self) -> float:
"""Return subtotal plus tax."""
return round(self.subtotal * (1 + self.tax_rate), 2)
def confirm(self) -> None:
"""Mark the order as confirmed."""
self.status = "confirmed"
def __str__(self) -> str:
return f"Order({self.order_id}, {self.customer}, {self.status})"
def __repr__(self) -> str:
return f"Order(order_id={self.order_id!r}, customer={self.customer!r})"
order = Order("ORD-001", "BensonCo", 100.00)
print(order.total()) # 108.0
order.confirm()
print(order) # Order(ORD-001, BensonCo, confirmed)
print(repr(order)) # Order(order_id='ORD-001', customer='BensonCo')

__init__ is not a constructor in the C# sense — the object already exists when it is called. It initializes the instance. self is the instance itself, passed implicitly as the first argument to every method.

class Counter:
count = 0 # class attribute
def __init__(self, name: str) -> None:
self.name = name # instance attribute
Counter.count += 1
@classmethod
def get_count(cls) -> int:
return cls.count
c1 = Counter("first")
c2 = Counter("second")
print(Counter.get_count()) # 2

A class attribute is shared across all instances. If you assign self.count = 0 on an instance, it creates a new instance attribute that shadows the class attribute for that instance only — the class attribute is unaffected.

class ShippedOrder(Order):
"""An order that has been dispatched."""
def __init__(self, order_id: str, customer: str, subtotal: float, tracking: str) -> None:
super().__init__(order_id, customer, subtotal)
self.tracking = tracking
self.status = "shipped"
def estimated_delivery(self, days: int) -> str:
from datetime import date, timedelta
arrival = date.today() + timedelta(days=days)
return arrival.strftime("%Y-%m-%d")
def __str__(self) -> str:
return f"ShippedOrder({self.order_id}, tracking={self.tracking})"
shipped = ShippedOrder("ORD-002", "NovaCorp", 250.00, "1Z999AA10123456784")
print(shipped.total()) # 270.0 — inherited from Order
print(shipped.estimated_delivery(3))
print(isinstance(shipped, Order)) # True

super() delegates to the parent class. In Python’s multiple inheritance, super() follows the Method Resolution Order (MRO) — the linearized chain of base classes. Use ClassName.__mro__ to inspect it.

Properties let you expose an attribute-like interface while running code on get and set. They replace the C#-style getter/setter pattern:

class PricedItem:
def __init__(self, name: str, price: float) -> None:
self.name = name
self._price = price # leading underscore: private by convention
@property
def price(self) -> float:
return self._price
@price.setter
def price(self, value: float) -> None:
if value < 0:
raise ValueError(f"Price cannot be negative, got {value}")
self._price = value
@price.deleter
def price(self) -> None:
del self._price
item = PricedItem("Widget", 9.99)
print(item.price) # 9.99
item.price = 12.50 # calls the setter
print(item.price) # 12.50
try:
item.price = -1
except ValueError as e:
print(e) # Price cannot be negative, got -1

Dunder (double-underscore) methods hook into Python’s built-in operations. Implementing them makes your objects behave like built-ins.

class OrderBatch:
def __init__(self, orders: list) -> None:
self._orders = orders
# len(batch)
def __len__(self) -> int:
return len(self._orders)
# batch[0]
def __getitem__(self, index: int):
return self._orders[index]
# for order in batch
def __iter__(self):
return iter(self._orders)
# order in batch
def __contains__(self, order) -> bool:
return order in self._orders
# batch1 + batch2
def __add__(self, other: "OrderBatch") -> "OrderBatch":
return OrderBatch(self._orders + other._orders)
# == comparison
def __eq__(self, other: object) -> bool:
if not isinstance(other, OrderBatch):
return NotImplemented
return self._orders == other._orders
o1 = Order("ORD-001", "BensonCo", 100.00)
o2 = Order("ORD-002", "NovaCorp", 200.00)
batch = OrderBatch([o1, o2])
print(len(batch)) # 2
print(batch[0]) # Order(ORD-001, BensonCo, pending)
for order in batch:
print(order.order_id)
Dunder Triggered by
__init__ Object initialization
__str__ str(obj), print(obj)
__repr__ repr(obj), in REPL
__len__ len(obj)
__getitem__ obj[key]
__iter__ for x in obj
__contains__ x in obj
__eq__ obj == other
__lt__, __gt__ etc. Comparison operators
__add__ obj + other
__enter__, __exit__ with obj:

Dataclasses: a shortcut for data-holding classes

Section titled “Dataclasses: a shortcut for data-holding classes”

For classes that primarily hold data, @dataclass generates __init__, __repr__, and __eq__ automatically:

from dataclasses import dataclass, field
@dataclass
class Product:
sku: str
name: str
price: float
tags: list[str] = field(default_factory=list)
def discounted_price(self, pct: float) -> float:
return round(self.price * (1 - pct), 2)
p = Product(sku="WIDGET-01", name="Widget", price=29.99, tags=["sale"])
print(p) # Product(sku='WIDGET-01', name='Widget', price=29.99, tags=['sale'])
print(p.discounted_price(0.10)) # 26.99
  • Mutable default argument in __init__. def __init__(self, items=[]) shares the same list across all instances. Use items=None and assign self.items = items or [] inside the body.
  • Forgetting self. Methods must accept self as the first parameter. A method without self is a function at the class level but cannot access the instance.
  • Modifying a class attribute via self. self.count += 1 creates a new instance attribute if count is a class attribute. Use ClassName.count += 1 to modify the class attribute.
  • Implementing __eq__ without __hash__. If you define __eq__, Python sets __hash__ to None, making instances unhashable (they can’t be put in a set or used as dict keys). Define __hash__ explicitly or use @dataclass(frozen=True).

1. What is the difference between __str__ and __repr__? __str__ is for end users — it should be readable and human-friendly. __repr__ is for developers — it should be unambiguous and ideally eval-able back to the object (eval(repr(obj)) == obj where possible). When only one is defined, Python falls back to __repr__ for both. In production code, always define __repr__ on custom classes.

2. How does multiple inheritance work in Python? Python uses the C3 linearization algorithm to compute the Method Resolution Order. When you call super() or access a method, Python walks the MRO to find the first class that implements it. SomeClass.__mro__ shows the order. The practical implication: super() in multiple inheritance doesn’t necessarily call the direct parent; it calls the next class in the MRO.

3. Senior scenario: an OrdersPortal codebase has 20 classes with similar validate() methods that all check the same three things, then do type-specific validation. How would you design this in Python? Use a base class with a template-method pattern: BaseValidator.validate() calls three shared checks then calls self._validate_specific(), which subclasses override. Alternatively, extract the shared checks into a mixin class and compose them. For more complex scenarios, use an abstract base class (abc.ABC) with @abstractmethod on _validate_specific to enforce that every subclass provides it. This prevents the base validate() from being called on a class that forgot to implement the type-specific step.

  • __init__ initializes an instance; self is passed implicitly to every method.
  • Class attributes are shared; instance attributes are per-object.
  • super() follows the MRO, which matters most in multiple inheritance.
  • Use @property for controlled attribute access with validation.
  • Dunder methods hook into Python built-in operations (len, in, +, with).
  • Use @dataclass for data-holding classes to avoid boilerplate.