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
Verify
Trace the line.
The point: write the order down and walk along it, down for the calls and up for the returns.
Making Noor
| Step | Class | Receives | Keeps | Passes on |
|---|---|---|---|---|
| 1 | WorkingStudent | name, school, company | nothing | all three |
| 2 | Student | school, rest | school (on the way back) | name, company |
| 3 | Employee | company, rest | company | name |
| 4 | Person | name, rest | name | nothing |
| 5 | object | nothing |
vars(noor).Checks for every join class
- 1
Print the MRO
Is the class that should wrap left of the wrapped one?
- 2
Count constructors
Each parent exactly once. Put a counter into a test.
- 3
Look at the fields
vars(obj)shows every field once. A missing one means that somebody did not callsuper(). - 4
List shared names
Compare the public names of the parents. For each shared one: same promise or only the same word?
- 5
Swap the parents
If the tests still pass, the order does not matter. If not, write a comment that says why.
Python
def shared_names(*parents): seen = {} for p in parents: for c in p.__mro__[:-1]: # without object for name in vars(c): if not name.startswith("__"): seen.setdefault(name, set()).add(c.__name__) return {n: sorted(cs) for n, cs in seen.items() if len(cs) > 1}class Printer: def start(self): ... def print_job(self): ...class Scanner: def start(self): ... def scan(self): ...print(shared_names(Printer, Scanner)) # {'start': ['Printer', 'Scanner']}