The MRO is the list of classes Python searches for an attribute, left to right. Python computes it with the C3 linearization when it creates the class.
1
classBase:
2
defsave(self) -> str:
3
return"Base"
4
5
6
classTimestamped(Base):
7
defsave(self) -> str:
8
return"Timestamped>"+super().save()
9
10
11
classValidated(Base):
12
defsave(self) -> str:
13
return"Validated>"+super().save()
14
15
16
classOrder(Timestamped, Validated): # a diamond: both parents share Base
17
pass
18
19
20
print([c.__name__for c in Order.__mro__])
21
print(Order().save()) # super() in Timestamped reaches its sibling, Validated
22
print(next(c.__name__for c in Order.__mro__if"save"invars(c))) # first match
23
print([c.__name__for c inbool.__mro__], [c.__name__for c inKeyError.__mro__])
object.__init__() takes exactly one argument (the instance to initialize)
Why does the error name object?
No class in the chain takes tll, so it reaches object.__init__(), which accepts no arguments besides the instance. The message does not name the bad keyword, but a misspelled option fails loudly instead of being ignored.
Rule
Why
every method in the chain calls super() once
each class runs exactly once
a root class ends the chain without super().method()
Rule of thumb: inherit for is-a, when the child can replace the parent everywhere (Liskov substitution). Compose for has-a, for swappable parts and to reuse a few methods. When in doubt, compose.
Polymorphism means one call works on many types: each type gives its own behavior. Python finds the method at run time on the object’s class, so the types need no common base. This is duck typing: “if it has area(), it is a shape”.
1
import io
2
import math
3
4
5
classCircle:
6
def__init__(self, r: float) -> None:
7
self.r = r
8
9
defarea(self) -> float:
10
return math.pi *self.r**2
11
12
13
classSquare: # no common base class with Circle
14
def__init__(self, side: float) -> None:
15
self.side = side
16
17
defarea(self) -> float:
18
returnself.side**2
19
20
21
deftotal_area(shapes: list) -> float:
22
returnround(sum(s.area() for s in shapes), 2) # any object with area()
23
24
25
defwrite_report(fp, lines: list[str]) -> None: # any object with write()
26
for line in lines:
27
fp.write(line +"\n")
28
29
30
buf = io.StringIO() # a file-like object in memory: a test double for a real file
Duck typing in the standard library: json.dump() takes any object with write(); csv.reader() takes any iterable of strings; sum() takes any iterable; with takes any object with __enter__ and __exit__.
When behavior depends on the type of an argument you do not own, use functools.singledispatch instead of an isinstance() chain:
Child __init__ replaces the parent’s. Symptom: AttributeError for an attribute the parent sets. Fix: call super().__init__(...).
super() is not “my parent”. Symptom: in a diamond, super() reaches a sibling class. Fix: read Cls.__mro__; design every class of the chain to cooperate.
Parent.method(self) in a chain. Symptom: a class runs twice or never. Fix: use super() in every class.
Root calls super().method(). Symptom: AttributeError: 'super' object has no attribute 'method'. Fix: the root class ends the chain.
Positional arguments in cooperative __init__. Symptom: values land in the wrong class when the MRO changes. Fix: keyword-only arguments and **kwargs.
Mixin on the right. Symptom: when the base class also defines the method (for example __repr__), the base’s version wins. Fix: list mixins before the main base class.
Impossible MRO. Symptom: TypeError: Cannot create a consistent method resolution order. Fix: list a child before its parent, or drop the redundant base.
Subclassing dict or list. Symptom: update(), __init__() or extend() skip your override. Fix: subclass UserDict / UserList or a collections.abc class.
Subclass breaks the contract. Symptom: code that works with the parent fails or gives wrong results with the child. Fix: keep the parent’s arguments, return types and errors; otherwise compose.
type(obj) is Base. Symptom: False for every subclass. Fix: isinstance(obj, Base).
isinstance() chains. Symptom: each new type means editing the chain. Fix: a method on each class, or singledispatch.
except AttributeError around a whole call. Symptom: real bugs inside the method are hidden. Fix: guard only the attribute lookup.
Deep hierarchies. Symptom: a small parent change breaks distant children. Fix: keep trees shallow; prefer composition.