Multiple inheritance
hard 50 minA class with several parent classes gets the types, the methods and the fields of all of them.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Two parents, one object: who is called, who sets which field, and what goes wrong.
Operations
Cooperative construction
Arguments travel down the line. Each class takes its own.
Step 1 of 6
One call for all
Name, school and company enter at the bottom class.
Step 1: One call for all
class Person: def __init__(self, *, name, **rest): super().__init__(**rest) self.name = nameclass Student(Person): def __init__(self, *, school, **rest): super().__init__(**rest) self.school = schoolclass Employee(Person): def __init__(self, *, company, **rest): super().__init__(**rest) self.company = companyclass WorkingStudent(Student, Employee): pass- Good for
- Parents you own
- Costs
- Keywords everywhere
- Each constructor runs
- once
Take yours, pass the rest, always call super.
In the real world
The same multiple inheritance doing real jobs. Pick one and step through it.
Python looks for a name from left to right and stops at the first hit.
Step 1 of 4
study()
| Working | Student | Employee | Person | object | |
|---|---|---|---|---|---|
| study() | no | found | |||
| work() | |||||
| eat() | |||||
| fly() |
Not in WorkingStudent, found in Student.
Step 1: study()
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Calling parents by name
criticalWith a shared ancestor its constructor runs twice.
WrongStudent.__init__(self, name, school)Employee.__init__(self, name, company)Rightsuper().__init__(name=name, school=school, company=company)Positional arguments
criticalsuper may call a sibling with another list of arguments.
Wrongsuper().__init__(name)Rightsuper().__init__(**rest)Mixin on the right
majorThe main class answers first, the mixin is never reached.
Wrongclass S(Server, LogMixin): passRightclass S(LogMixin, Server): passOne method for two promises
criticalOne caller gets the wrong behaviour without an error.
Wrongclass Copier(Printer, Scanner): ...Rightcopier.as_scanner().start()Parent for a side that ends
majorAn object keeps its class, people do not keep their jobs.
Wrongclass WorkingStudent(Student, Employee)Rightperson.take_role(EmployeeRole, job)
Interview tips
Three kinds
- Type: harmless
- Behaviour: needs an order
- State: needs a plan
Show the order
- Print `__mro__`
- Walk it aloud
- Say who ends the chain
Test the join
- Each constructor once
- All fields present
- Shared names listed
Offer the way out
- Roles for sides that end
- Wrappers for extras
- Adapters for foreign classes