Object-oriented programming
Classes, instances, inheritance, dunder methods, properties, dataclasses and enums.
Classes, instances and __init__
A class is a blueprint; __init__ sets up each new instance's own data when it is created.
class Dog: defines a new type, and calling Dog("Rex", 3) creates a new instance of it, automatically calling __init__(self, ...) to set up that instance's own attributes — self.name = name stores data specific to this particular dog, not shared with any other Dog instance. An ordinary instance method — a plain function defined in the class body — automatically receives the calling instance as its first parameter, self, so it can read and modify that instance's own attributes; methods marked @staticmethod or @classmethod, and properties, behave differently and are covered later. Each instance has its own attribute namespace, so reassigning one instance's attribute never reassigns another instance's — but an attribute's value is a reference, so two instances can still end up pointing at the exact same mutable object if that object is passed to both.
Key points
- class defines a type; calling it like a function creates a new instance
- __init__(self, ...) sets up an instance's own attributes when it is created
- Each instance has its own attribute namespace, but attribute values are references — two instances can still share the same mutable object
Code
Run the code to see the result.
Two independent Dog instances, each with its own name and age set by __init__.
Common pitfalls
- Forgetting self as the first parameter of a method raises a TypeError when it is called
- Setting a mutable default like self.items = [] as a class attribute (outside __init__) shares one list across every instance
Practice exercise
Write a BankAccount class with __init__(self, owner, balance=0), a deposit(amount) method and a withdraw(amount) method that refuses to overdraw.
Inheritance and super()
A subclass reuses and extends a parent class's behavior instead of duplicating it.
class Puppy(Dog): makes Puppy a subclass of Dog: an attribute or method not found directly on a Puppy instance or the Puppy class is looked up on Dog next, following Python's method resolution order (MRO) — so a subclass effectively has access to everything its bases define, without any of it being copied. A Puppy instance is also considered a Dog for isinstance() checks. Overriding a method in the subclass replaces the parent's version for instances of the subclass, but super().method(...) lets the override call the next implementation in the MRO first and add to it, rather than fully rewriting it — in simple single inheritance like this, that next implementation is the direct parent, which is commonly used inside an overridden __init__ to let it set up shared attributes before the subclass adds its own.
Key points
- class Child(Parent): attribute lookup falls through to Parent via the MRO when not found on Child
- Overriding a method replaces the parent's version for the subclass
- super().method(...) calls the next implementation in the MRO — the direct parent in simple single inheritance
Code
Run the code to see the result.
Puppy reuses Dog's __init__ via super() and extends speak() instead of rewriting it from scratch.
Common pitfalls
- Overriding __init__ without calling super().__init__() means the parent's setup never runs
- Deep inheritance chains (more than 2-3 levels) usually become harder to reason about than composition
Practice exercise
Given a Shape base class with an area() method returning 0, write Rectangle and Circle subclasses that override area() correctly, and a shared describe() method inherited by both.
Dunder methods: __repr__, __eq__ and friends
Special double-underscore methods let your own classes work with print(), ==, len() and other built-ins.
Defining __repr__(self) controls what a debugger, REPL or repr() shows for an instance; without it, Python's default is an unhelpful <Point object at 0x...>. Defining __eq__(self, other) controls what == means for two instances — without it, == falls back to identity comparison (is), so two logically-equal objects would incorrectly compare as unequal. Other common dunders include __len__ (for len(obj)), __lt__ (for <, and sorting), and __add__ (for +); implementing the right ones makes a custom class behave like a natural extension of the language rather than a foreign object.
Key points
- __repr__ controls how an instance is displayed in the REPL, debugger and repr()
- __eq__ controls == behavior; without it, == falls back to identity (is)
- __len__, __lt__, __add__ hook a custom class into len(), sorting, and + respectively
Code
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
print(Point(1, 2) == Point(1, 2)) # TrueA Point class with a useful repr and value-based equality instead of the defaults.
Common pitfalls
- Without __eq__, Point(1, 2) == Point(1, 2) is False because it falls back to identity comparison
- Defining __eq__ without also defining __hash__ makes instances unhashable, breaking use as dict keys or set members
Practice exercise
Add __repr__ and __eq__ to a Money class holding amount and currency, so two Money instances with the same amount and currency compare equal and print readably.
Properties: computed and validated attributes
@property lets a method be accessed like a plain attribute, enabling validation without changing the calling code.
A method decorated with @property can be read using plain attribute syntax, obj.value instead of obj.value(), which lets a class start with a simple public attribute and later evolve it into computed or validated logic without breaking any code that already reads obj.value. Pairing it with a @value.setter-decorated method lets assignment (obj.value = 5) run validation logic too — raising a ValueError for an invalid value — while still looking, to the outside world, exactly like ordinary attribute assignment.
Key points
- @property makes a method readable with plain attribute syntax, obj.value
- @x.setter lets obj.x = value run validation logic before storing it
- Callers see no difference between a plain attribute and a property
Code
Run the code to see the result.
A computed read-only fahrenheit property, plus a validated celsius property with a setter.
Common pitfalls
- Defining only a getter (no setter) makes the attribute read-only; obj.celsius = 5 then raises AttributeError
- Overusing properties for simple data with no validation or computation adds indirection without benefit
Practice exercise
Add a validated width property to a Rectangle class that rejects negative values with a ValueError, and a read-only area property computed from width and height.
@dataclass for data-holding classes
@dataclass generates __init__, __repr__ and __eq__ from annotated fields, removing common boilerplate.
Decorating a class with @dataclass and listing its fields as type-annotated class attributes automatically generates __init__ (accepting each field as a parameter), a readable __repr__, and a field-by-field __eq__, all without writing them by hand. field(default_factory=list) handles a mutable default correctly (unlike a plain = [], which would be shared across instances the same way a function's mutable default is). @dataclass(frozen=True) additionally prevents normal field reassignment after __init__ and, with the default equality settings, normally enables a generated __hash__ — but it does not create true deep immutability, since a mutable object stored in a field can still be mutated through that object's own methods, and the instance is only actually hashable if every field value participating in the hash is itself hashable.
Key points
- @dataclass generates __init__, __repr__ and __eq__ from annotated fields
- field(default_factory=list) is the correct way to give a mutable default
- frozen=True blocks field reassignment and normally enables hashing, but does not deep-freeze mutable field values
Code
Run the code to see the result.
A Task dataclass with a required field, a default, and a correctly-handled mutable default list.
Common pitfalls
- tags: list = [] (a plain mutable default, not field(default_factory=list)) raises a ValueError in a dataclass
- @dataclass generates useful dunders, but a class with significant custom behavior is often better as a plain class
Practice exercise
Write a @dataclass Product with name, price, and an in_stock bool defaulting to True, then create two Products and confirm they compare equal only when all fields match.
Enum, StrEnum and named states
Enums replace scattered magic strings and numbers with a fixed, explicit set of named values.
Enum defines a closed set of named values such as states, modes or result kinds. Code can then compare Status.READY instead of repeating fragile strings like "ready" across many files. StrEnum is useful when enum members also need to behave like strings at serialization or API boundaries, while IntEnum exists for integer-compatible protocols; ordinary Enum should remain the default when compatibility with a primitive type is not required. Enum members are singletons, so identity checks between members are stable, and construction such as Status("ready") validates an external value by either returning the matching member or raising ValueError. Enums model a fixed vocabulary; they are not a replacement for classes that need substantial per-instance state.
Key points
- Enum gives a fixed set of named values and removes repeated magic strings or numbers
- StrEnum is convenient at string serialization/API boundaries; use ordinary Enum when primitive compatibility is unnecessary
- Constructing an enum from an external value validates it and raises ValueError for an unknown value
Code
Run the code to see the result.
A StrEnum turns external string states into validated named values before business logic uses them.
Common pitfalls
- Comparing an Enum member to its raw primitive value is usually a design smell unless you intentionally chose StrEnum or IntEnum
- Changing an enum value that is stored in a database or sent over an API is a compatibility change
- An enum is for a fixed set of alternatives, not for arbitrary user-created values
Practice exercise
Define a StrEnum Environment with DEV, STAGE and PROD values, parse the string "stage" into the enum, and write a function that allows destructive test data cleanup only for non-PROD values.