Object-Oriented Programming in Python: Classes, Inheritance, and Dunder Methods
What you’ll learn
Section titled “What you’ll learn”- 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.
Summary
Section titled “Summary”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+).
Defining a class
Section titled “Defining a class”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.0order.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.
Instance vs class attributes
Section titled “Instance vs class attributes”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()) # 2A 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.
Inheritance
Section titled “Inheritance”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 Orderprint(shipped.estimated_delivery(3))print(isinstance(shipped, Order)) # Truesuper() 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
Section titled “Properties”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.99item.price = 12.50 # calls the setterprint(item.price) # 12.50
try: item.price = -1except ValueError as e: print(e) # Price cannot be negative, got -1Key dunder methods
Section titled “Key dunder methods”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)) # 2print(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
@dataclassclass 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.99Common mistakes
Section titled “Common mistakes”- Mutable default argument in
__init__.def __init__(self, items=[])shares the same list across all instances. Useitems=Noneand assignself.items = items or []inside the body. - Forgetting
self. Methods must acceptselfas the first parameter. A method withoutselfis a function at the class level but cannot access the instance. - Modifying a class attribute via
self.self.count += 1creates a new instance attribute ifcountis a class attribute. UseClassName.count += 1to modify the class attribute. - Implementing
__eq__without__hash__. If you define__eq__, Python sets__hash__toNone, making instances unhashable (they can’t be put in a set or used as dict keys). Define__hash__explicitly or use@dataclass(frozen=True).
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”__init__initializes an instance;selfis 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
@propertyfor controlled attribute access with validation. - Dunder methods hook into Python built-in operations (
len,in,+,with). - Use
@dataclassfor data-holding classes to avoid boilerplate.
Related pages
Section titled “Related pages”- Python error handling — the next article in this series
- Magic methods deep dive — full dunder method reference
- Dataclasses feature guide —
@dataclassoptions and patterns - MRO and super — multiple inheritance in depth
Official references
Section titled “Official references”- Python docs: Classes — official tutorial chapter
- Python docs: Data model — complete dunder method reference
- Python docs: dataclasses —
@dataclassreference