Multiple inheritance
hard 50 minA class with several parent classes gets the types, the methods and the fields of all of them.
Watch lesson4:37
When cooperation fails
One link cuts the chain.
The point: cooperative inheritance works only if every class in the line plays along, including the ones you did not write.
class Base: def __init__(self, **rest): super().__init__(**rest)class Stubborn(Base): def __init__(self, **rest): self.kind = "stubborn" # forgot super().__init__class Counter(Base): def __init__(self, **rest): super().__init__(**rest) self.count = 0class Both(Stubborn, Counter): passprint(hasattr(Both(), "count")) # False: Counter was never askedclass Vendor: # third party, not cooperative def __init__(self, path): self.path = pathclass HasVendor(Base): # adapter: hold it, do not extend it def __init__(self, *, path, **rest): super().__init__(**rest) self.vendor = Vendor(path)class Good(HasVendor, Counter): passg = Good(path="/tmp/x")print(g.vendor.path, g.count) # /tmp/x 0Failure walk: the missing counter
- 1
Monday
class Both(Stubborn, Counter)is added. The constructor of Stubborn does not callsuper(). - 2
It starts
Objects are made without an error. The field
countdoes not exist. - 3
An hour later
The first request that counts raises AttributeError, far away from the cause.
- 4
A wrong fix
Somebody sets
self.count = 0in the join. Now a change in Counter is never seen. - 5
The right fix
Stubborn calls
super().__init__(**rest). A test makes every join class and compares its fields with the expected ones.
Where the line is cut
Agreement
Six rules that keep the line whole
Rules for a cooperative method
| Rule | Without it |
|---|---|
Same signature in the whole family, or keywords with **rest | TypeError in some combinations |
| A root class that ends the chain | AttributeError: object has no such method |
Everybody calls super(), the root does not | Some classes get no turn |
| Nobody names a parent directly | A class is called twice or skipped |
| Foreign classes are wrapped, not extended | The chain ends at the foreign class |
| Do not rely on being last | The line of a subclass may put others behind you |
You must combine your cooperative Counter with a vendor class that ignores super().
BreaksVendor first
- How
class Good(Vendor, Counter).- Limit
- The vendor's constructor never reaches Counter.
- Choose when
- Never.
WorksVendor last
- How
class Good(Counter, Vendor), with the arguments of the vendor passed as the rest.- Limit
- Works until the vendor class gets a parent, or a second foreign class joins.
- Choose when
- One foreign class, pinned version.
StrongAn adapter that holds it
- How
- A cooperative class that keeps the vendor object as a field.
- Limit
- Not an instance of the vendor class. Forward what is needed.
- Choose when
- The default.