CS Fundamentals Trainer · Guides

Python classes, inheritance and typing

Attribute lookup, the MRO and super(), properties and descriptors, dataclasses and what they cost, abstract base classes, Protocols, and what type hints do and do not guarantee at runtime.

16 min read

Classes in Python are less special than they look. A class is an object, an instance is an object with a dictionary of attributes and a link to its class, and nearly everything a class does (attribute access, property, method calls, operators, super()) is a lookup rule you can read and test. Type hints, meanwhile, are comments the interpreter keeps but never checks. This guide covers how attribute lookup and inheritance really work, what @property and descriptors are, what dataclasses generate, when an abstract base class or a Protocol fits, and what type hints do and do not guarantee. Every claim comes with a script run on CPython 3.13 (in the appendix). It assumes you have read how Python works, in particular the section on special methods.

One limit up front: the sandbox where I ran these scripts had no type checker installed (mypy, pyright), so this guide describes what checkers do from their documentation, and every output shown is from the running interpreter.

1. Attribute lookup

When you write obj.name, Python searches in a fixed order:

  1. A data descriptor on the class (for example a property or anything defining __set__) wins first.
  2. Then the instance's own __dict__.
  3. Then non-data descriptors and plain attributes on the class, following the inheritance order (section 2).
  4. Finally __getattr__, if the class defines it.

The practical effects, all tested:

2. Inheritance and the method resolution order

A class can have several parents. Python flattens the hierarchy into one list, the method resolution order (MRO), computed by the C3 linearisation algorithm. A lookup walks that list left to right and uses the first match. For the classic diamond (D(B, C), where B and C both extend A) the MRO was:

['D', 'B', 'C', 'A', 'object']

A comes after both of its children, and object is always last. If the parents are listed in a contradictory order, Python refuses to build the class: class X(A, B) where B already extends A raised TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B.

What super() really does

super() does not mean "my parent". It means "the next class after me in the MRO of the object's actual type". That is what makes cooperative multiple inheritance work. In the diamond, each hello method added its own name and called super().hello(); calling D().hello() gave:

['D', 'B', 'C', 'A']

B's super() went to C, not to A, because C is next in the MRO of a D. Every class in the chain ran exactly once. The rules that keep this working: call super() in every cooperating method, accept *args, **kwargs and pass them along when the signatures differ, and keep __init__ methods cooperative.

Inheritance or composition?

Inheritance says "is a"; composition says "has a". Inheritance couples a subclass to every detail of its parent (a change in the parent's internals can break the child), so prefer composition by default: hold another object and delegate to it. Use inheritance when the subclass really is a specialisation that can stand in anywhere the parent is accepted (the Liskov substitution principle), when a framework requires it, or for small mixins that add one behaviour. If you reach for multiple inheritance of real state, stop and reconsider.

__init_subclass__ lets a base class react when it is subclassed, which replaces many uses of metaclasses. A Plugin base that appended each subclass name to a registry produced ['P1', 'P2'] after two subclasses were defined, with no decorator or metaclass.

3. Properties and descriptors

A property turns method calls into attribute access, so you can start with a plain attribute and add validation later without changing callers:

class Temp:
    @property
    def celsius(self): return self._c
    @celsius.setter
    def celsius(self, v):
        if v < -273.15: raise ValueError("below absolute zero")
        self._c = v
    @property
    def fahrenheit(self): return self._c * 9 / 5 + 32     # computed, read-only

Setting t.celsius = -300 raised ValueError: below absolute zero, and assigning to t.fahrenheit raised AttributeError: property 'fahrenheit' of 'Temp' object has no setter. This is why Python code does not write getters and setters up front: a public attribute can become a property later without breaking anyone.

A property is built on the descriptor protocol: any object on a class with __get__, and optionally __set__ or __set_name__, controls access to the attribute it is stored under. I wrote a reusable Positive descriptor and used it for two fields of an Item class; Item(5, 2) worked (price times quantity gave 10) and Item(-1, 1) raised ValueError: must be positive. Functions, classmethod, staticmethod and __slots__ are all descriptors too. You will rarely write one, but it explains how the language behaves.

__repr__ and __str__

repr() is for developers and should be unambiguous (ideally something you could paste back into code); str() is for readers. If a class defines only __repr__, str() falls back to it, which is what I saw: str(P("a")), repr(P("a")) and the repr of a list containing it were all P('a'). Always define __repr__; it is what you see in logs and tracebacks.

4. Dataclasses

A class that mostly stores fields needs the same boilerplate every time: __init__, __repr__, __eq__. The @dataclass decorator generates it from the annotations:

@dataclass
class Point:
    x: int
    y: int = 0

Point(1, 2) printed as Point(x=1, y=2), compared equal to another Point(1, 2) and was not the same object. The options that matter:

OptionWhat it doesWhat I saw
eq=True (default)generates __eq__, and sets __hash__ to None{p: 1} raised TypeError: unhashable type: 'Point'
frozen=Trueforbids assignment after creation, and generates __hash__assigning raised FrozenInstanceError; equal instances had equal hashes
order=Truegenerates <, <=, >, >= comparing fields as tuplessorted() ordered Version(0, 9), Version(1, 2), Version(1, 10)
slots=Trueuses __slots__ (3.10+)see the memory table below

Helpers: dataclasses.replace(obj, field=value) makes a modified copy (the way to "change" a frozen object), and asdict(obj) converts to a dict.

Mutable defaults are rejected. tags: list = [] raised ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory, protecting you from the shared-default bug. Write tags: list = field(default_factory=list); two instances then had separate lists (['x'] and []).

Choose by need: a dataclass for a mutable or frozen record with methods; a NamedTuple for a small immutable record that must also behave as a tuple; a plain dict for data of unknown shape; a class when behaviour dominates. For validating untrusted input (JSON from a request), a validation library such as pydantic checks types at runtime; dataclasses do not.

What a record costs

I created 500,000 two-field objects of each kind and divided the traced memory by the count:

KindBytes per object
plain class with __init__96
@dataclass96
@dataclass(slots=True)56
namedtuple72
tuple64

(The small integers inside are shared objects, so these figures are for the container only.) A dataclass is the same size as the hand-written class; slots=True removes the per-instance dictionary. This only matters when you hold millions of instances.

5. Abstract base classes

An abstract base class (ABC) declares methods that subclasses must provide. Python enforces it when you try to create an instance:

class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...
class Half(Shape): pass
Half()   # TypeError: Can't instantiate abstract class Half without an implementation for abstract method 'area'

A subclass that implemented area worked (Sq(3).area() gave 9). Use ABCs when you control a family of classes and want a failure at construction time rather than the first call. The collections.abc module has ready-made ones (Iterable, Mapping, Sequence) that you can inherit from or use with isinstance.

6. Type hints: what they are and are not

Annotations such as def double(n: int) -> int are stored and otherwise ignored when the program runs. I called double("ab") and got 'abab'; the hints were simply there in double.__annotations__. A dataclass field annotated n: int happily held the string 'not an int'. Hints are read by:

So hints give you early, cheap bug detection and better documentation if you run a checker in CI, and no protection at all otherwise. Useful habits:

Protocols: duck typing, written down

Python's native style is duck typing: if it has a close() method, treat it as closeable. A typing.Protocol lets you describe that shape so a checker can verify it, without requiring inheritance:

@runtime_checkable
class Closeable(Protocol):
    def close(self) -> None: ...

An F class with a close method counted as a Closeable without inheriting from anything (isinstance gave True), and a class without one did not (False). With @runtime_checkable, isinstance checks only that the methods exist, not their signatures or types; a static checker checks the rest. The choice between the two tools:

NeedUse
Accept any object with the right methods, including third-party classesProtocol
Share implementation and require subclasses to fill in methodsABC
Just a function that works on anything reasonableno declaration; document it

7. Common mistakes

8. Questions interviewers like to ask

"What is the MRO and what does super() do?"

The MRO is the linear order in which Python searches a class and its parents, computed by C3 linearisation (Class.__mro__). super() finds the next class after the current one in the MRO of the instance's type, so in a diamond each class runs once.

"What is the difference between a class attribute and an instance attribute?"

A class attribute is stored on the class and shared; an instance attribute is stored in the instance's __dict__ and shadows the class attribute on reads. Assigning through the instance never changes the class attribute, but mutating a shared mutable one does.

"How does @property work?"

It is a data descriptor stored on the class: reading calls the getter, assigning calls the setter, and there is no per-instance storage unless the getter and setter create it. It lets you add validation or computation without changing the attribute syntax.

"@dataclass, NamedTuple or a plain class?"

A dataclass for a record that may be mutable and have methods; NamedTuple for an immutable tuple-like record; a plain class when behaviour matters more than fields. Use frozen=True for hashable records, and slots=True when you have millions of them.

"Do type hints make Python statically typed?"

No. The interpreter ignores them. They help only if a checker runs, and for libraries that read them at runtime.

"Protocol or ABC?"

A Protocol describes structure and works with classes that do not inherit from it (structural subtyping); an ABC is nominal, enforces implementation at construction and can carry shared code.

"Why is __eq__ without __hash__ a problem?"

Defining __eq__ sets __hash__ to None, so instances become unhashable and cannot be dict keys or set members.

9. Things to mention in an interview

Quick recap

Appendix: the experiment code

Python 3.13 (CPython), standard library only. Run each file with python3 file.py. The exact wording of error messages and the per-object sizes can differ between Python versions.

mro.py: lookup order, the MRO and super(), properties, a descriptor, __repr__ and __init_subclass__:

# 1. method resolution order and super()
class A:
    def hello(self): return ["A"]
class B(A):
    def hello(self): return ["B"] + super().hello()
class C(A):
    def hello(self): return ["C"] + super().hello()
class D(B, C):
    def hello(self): return ["D"] + super().hello()
print("MRO:", [k.__name__ for k in D.__mro__])
print("D().hello():", D().hello())

# 2. inconsistent hierarchy
try:
    class X(A, B): pass
except TypeError as e: print("TypeError:", e)

# 3. attribute lookup order: data descriptor > instance dict > class attr
class Temp:
    def __init__(self): self._c = 0
    @property
    def celsius(self): return self._c
    @celsius.setter
    def celsius(self, v):
        if v < -273.15: raise ValueError("below absolute zero")
        self._c = v
    @property
    def fahrenheit(self): return self._c * 9 / 5 + 32
t = Temp(); t.celsius = 100
print("fahrenheit:", t.fahrenheit)
try: t.celsius = -300
except ValueError as e: print("ValueError:", e)
try: t.fahrenheit = 1
except AttributeError as e: print("AttributeError:", e)

class Shadow:
    x = "class"
s = Shadow(); print("before:", s.x); s.x = "instance"; print("after:", s.x, "| class still:", Shadow.x)
# methods are functions bound on access
class K:
    def m(self): return 1
k = K()
print("bound method:", k.m.__self__ is k, "| same function:", K.m is K.__dict__["m"])

# 4. a descriptor
class Positive:
    def __set_name__(self, owner, name): self.name = "_" + name
    def __get__(self, obj, owner): return self if obj is None else getattr(obj, self.name)
    def __set__(self, obj, v):
        if v <= 0: raise ValueError("must be positive")
        setattr(obj, self.name, v)
class Item:
    price = Positive()
    qty = Positive()
    def __init__(self, price, qty): self.price = price; self.qty = qty
i = Item(5, 2); print("descriptor ok:", i.price * i.qty)
try: Item(-1, 1)
except ValueError as e: print("descriptor rejects:", e)

# 5. __repr__ vs __str__
class P:
    def __init__(self, n): self.n = n
    def __repr__(self): return f"P({self.n!r})"
print(str(P("a")), repr(P("a")), [P("a")])

# 6. isinstance vs type
class Base: pass
class Sub(Base): pass
print(isinstance(Sub(), Base), type(Sub()) is Base)
# 7. __init_subclass__ registry
registry = []
class Plugin:
    def __init_subclass__(cls, **kw): super().__init_subclass__(**kw); registry.append(cls.__name__)
class P1(Plugin): pass
class P2(Plugin): pass
print("registered:", registry)

dc_typing.py: dataclasses and their options, annotations at runtime, an ABC, a Protocol and the memory of record types:

import sys, tracemalloc
from dataclasses import dataclass, field, replace, asdict, FrozenInstanceError
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable, Optional

# dataclass gives __init__, __repr__, __eq__
@dataclass
class Point:
    x: int
    y: int = 0
p = Point(1, 2)
print(p, p == Point(1, 2), p is Point(1, 2))
# eq without frozen -> unhashable
try: {p: 1}
except TypeError as e: print("TypeError:", e)

# frozen + order
@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int = 0
v = Version(1, 2)
try: v.major = 2
except FrozenInstanceError as e: print("FrozenInstanceError:", type(e).__name__)
print(sorted([Version(1, 10), Version(1, 2), Version(0, 9)]), hash(v) == hash(Version(1, 2)))
print("replace:", replace(v, minor=5), "| asdict:", asdict(v))

# mutable default
try:
    @dataclass
    class Bad:
        tags: list = []
except ValueError as e: print("ValueError:", e)
@dataclass
class Good:
    tags: list = field(default_factory=list)
a, b = Good(), Good(); a.tags.append("x"); print("default_factory:", a.tags, b.tags)

# annotations are not enforced at runtime
def double(n: int) -> int: return n * 2
print("double('ab') =", double("ab"), "| annotations:", double.__annotations__)
@dataclass
class Typed: n: int
print("dataclass does not validate:", Typed("not an int"))

# Optional / None handling
def first(xs: list[str]) -> Optional[str]: return xs[0] if xs else None
print("first([]) =", first([]))

# ABC enforcement
class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...
class Sq(Shape):
    def __init__(self, s): self.s = s
    def area(self): return self.s ** 2
class Half(Shape): pass
print("Sq area:", Sq(3).area())
try: Half()
except TypeError as e: print("TypeError:", e)

# Protocol: structural typing (duck typing + checkable)
@runtime_checkable
class Closeable(Protocol):
    def close(self) -> None: ...
class F:
    def close(self): pass
class NoClose: pass
print("isinstance Protocol:", isinstance(F(), Closeable), isinstance(NoClose(), Closeable))

# memory: plain vs dataclass vs slots dataclass vs tuple
@dataclass
class DC: a: int; b: int
@dataclass(slots=True)
class DS: a: int; b: int
class Plain:
    def __init__(self, a, b): self.a = a; self.b = b
from collections import namedtuple
NT = namedtuple("NT", "a b")
for name, mk in (("plain class", lambda: Plain(1, 2)), ("dataclass", lambda: DC(1, 2)), ("dataclass(slots=True)", lambda: DS(1, 2)), ("namedtuple", lambda: NT(1, 2)), ("tuple", lambda: tuple([1, 2]))):
    tracemalloc.start(); objs = [mk() for _ in range(500_000)]; cur, _ = tracemalloc.get_traced_memory(); tracemalloc.stop()
    print(f"{name:22s} {cur/500_000:6.0f} bytes each"); del objs

Sources

  1. Python documentation, Data model (special methods, __slots__, __init_subclass__, descriptors).
  2. Python documentation, Descriptor HowTo Guide, and The Python 2.3 Method Resolution Order (C3 linearisation).
  3. Python documentation, dataclasses, abc, typing and collections.abc.
  4. Python Enhancement Proposals: PEP 557: Data Classes, PEP 544: Protocols: Structural subtyping, PEP 484: Type Hints, PEP 487: Simpler customisation of class creation.
  5. Raymond Hettinger, Super considered super! (2011).
  6. mypy documentation, Type hints cheat sheet, and the typing specification at typing.python.org.

Practise this topic: Python

More guides