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
Multiple inheritance
1:01Reel
Theory
Read or listen first. About 2 min.
What it is
Multiple inheritance means that a class names more than one direct parent class: class WorkingStudent(Student, Employee). An object of it is a student and an employee at once, and it has the methods and fields of both.
It helps to split it in three. Multiple inheritance of type (many interfaces) exists in nearly every language. Of behaviour (methods with bodies) exists in many, as default methods, traits or mixins. Of state (fields and constructors) exists in few, such as C++, Python and Eiffel. Nearly all the trouble comes from state.
This page is about the feature itself: what a language must decide, how to write parents that get along, and when to choose something else. Two neighbours have pages of their own: the shared ancestor is in Diamond problem, and life without the feature is in Multiple parents in single inheritance.
Why it exists
Some things really have several independent sides. A threaded web server is a web server and is threaded. A product can be saved, has a price and has a label. One tree cannot show independent sides without copies.
Code can come from several sources without forwarding lines. class ThreadingHTTPServer(ThreadingMixIn, HTTPServer) is a whole class in one line.
And the type system sees it: the object can be handed to code that wants either parent.
A short history
1980
The Flavors system of the MIT Lisp Machine (A.I. Memo 602, November) builds classes by mixing several flavors.
1989
C++ 2.0 adds multiple inheritance, together with abstract classes.
1996
Java 1.0 leaves it out. The language white paper says that multiple inheritance and the problems it generates were discarded, and that interfaces bring its desirable features.
2014
Java 8 lets interfaces have method bodies: behaviour from many sources comes back, state does not.
Words to know
- Direct base
- A parent named in the class header.
- Join class
- The class where several parents meet.
- MRO
- Method resolution order: the line of classes that Python searches for a name.
- Cooperative method
- It does its own share and calls
super(), so every class in the line gets its turn. - Mixin
- A small parent made to be combined, not to stand alone.
- Name clash
- Two parents have a member with one name.
- Subobject
- In C++, the part of an object that belongs to one base class.
- Pointer adjustment
- Moving an address from the whole object to one of its subobjects.
- Virtual base
- In C++, a base that is shared instead of repeated.
- Orthogonal
- Independent: one side can change without the other.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Name the sides. Independent, small, and for life?
Understand it
Start here
A bus that is also a boat
Noor drives tourists through a town by the lake. A bus is good on the road, a boat is good on the water. So the town builds something that is both.
Frames 3 and 4 are the two prices of two parents: names and state. Frames 5 to 7 are three ways to pay.
Structure
Person, student, employee
The classic example. A working student studies at a school and works at a company. First as many people write it, then as it should be.
Bad: two persons in one student (C++ without virtual)
1/3Two good classes
A student is a person. An employee is a person. Each carries the fields of a person.
extends (is a)
Good: one person, two sides
1/4One root
Person owns the name. Nobody below stores a second one.
extends (is a)
Who is called by super() in describe
super() means the next class in the order of this object.Languages
Who supports what
| Language | Many parent classes | How | A clash of names |
|---|---|---|---|
| C++ | yes | Full; virtual bases share an ancestor | Error at the call, unless you qualify |
| Python | yes | Full; a search order, the MRO | First in the order wins, silently |
| Eiffel | yes | Full; parents can be adapted | Must be renamed |
| Java | no | One class, many interfaces with defaults | Compile error, you must override |
| C# | no | One class, many interfaces | Error, or implement each separately |
| TypeScript | no | One class, many interfaces, mixin functions | The last applied mixin wins |
| Ruby | no | One class, modules are included | The last included module wins |
| PHP | no | One class, traits | Error until insteadof chooses |
What you win
- Code from several sources without forwarding
- Things with two sides, such as a working student
- Types that fit in more than one place
- Independent features combined in one line
What you pay
- Ambiguity when an ancestor is shared
- Names that clash
- The order of parents is part of the meaning
- Harder to see where a method comes from
Rule 1
Order is meaning
In Python the class on the left is searched first. A mixin that wraps a method must stand left of the class it wraps. Python's own socketserver page says it: the mix-in class comes first, since it overrides a method of the server.
class Server: def handle(self, request): return f"done {request}"class LoggingMixin: def handle(self, request): print("log", request) return super().handle(request) # the next class in the orderclass LoggedServer(LoggingMixin, Server): # mixin first passclass WrongOrder(Server, LoggingMixin): # Server.handle is found first passprint(LoggedServer().handle("a")) # log a, done aprint(WrongOrder().handle("b")) # done b, and no logRule 2
Construction needs an agreement
Every parent wants its arguments. Nobody knows who comes next in the line. The agreement that works: keyword arguments only, take your own, pass the rest on, always call super().__init__.
class Person: def __init__(self, name): self.name = nameclass Student(Person): def __init__(self, name, school): super().__init__(name) # next in the order, not always Person self.school = schoolclass Employee(Person): def __init__(self, name, company): super().__init__(name) self.company = companyclass WorkingStudent(Student, Employee): def __init__(self, name, school, company): super().__init__(name, school) self.company = companytry: WorkingStudent("Noor", "Harbour College", "Blue Cafe")except TypeError as e: print(e) # Employee.__init__() missing 1 required positional argument: 'company'Arguments on their way down the line
object, it raises TypeError. That is good: a misspelled argument is found at once.Rule 3
A clash must be decided, not ignored
| The two parents | Example | What to do |
|---|---|---|
| Same promise, same meaning | describe() of Student and Employee | Cooperate: each does its share and calls super() |
| Same promise, two answers | Two defaults of greet() | Override in the join and choose |
| Same word, two promises | start() of a printer and of a scanner | Two names, or two objects. Never one method |
| Same field name by chance | _lock in two mixins | Private names: __lock in Python, private in C++ |
Judgement
Should this be a second parent?
Four questions
An order service class should log, retry and cache. Three parents?
BreaksThree full parents with state
- How
class OrderService(Logger, Retrier, Cache).- Limit
- A service is not a cache.
getof Cache andgetof the service clash, and the order of retry and cache is hidden in the header. - Choose when
- Never.
WorksCooperative mixins
- How
class S(LogMixin, RetryMixin, OrderService)where each wrapsfetchand callssuper().- Limit
- Fixed per class, order matters, hard to test one alone.
- Choose when
- Framework code with a stable set of hooks.
StrongWrappers
- How
- Decorator objects around one contract:
Logged(Retried(Cached(service))). - Limit
- A little wiring, and the self problem.
- Choose when
- The set of extras differs by place or time. See Decorator.
Four safe uses
Many interfaces
Abstract classes without fields. The C++ Core Guidelines recommend this use first (C.135).
Mixins
Small, without a life of their own, calling
super(). More in Mixins and traits.Type plus value
class Status(str, Enum): an enum whose members are also strings.One main class plus helpers
One parent says what it is, the others add finished steps.
Summary
The whole topic in one minute.
Many types are harmless, many behaviours need an order, many states need a plan. Ask which of the three you are about to inherit.
Parents that cooperate take keyword arguments, keep what is theirs, pass the rest on and always call super(). One parent that does not call it cuts the line.
When two parents use one name for two promises, or when a side can end during life, hold objects instead of extending classes.
- Type, behaviour, state: most trouble comes from state.
super()is the next class in the line of the object, not the parent you think of.- Keyword arguments, take yours, pass the rest, always call super.
- Mixins stand on the left.
- One word with two promises needs two names or two objects.
- If a side can end, it is a role to hold, not a parent.
Sources
- Python: super()
- Python tutorial: multiple inheritance
- Raymond Hettinger: Python's super() considered super
- Python: socketserver
- Python: http.server
- Python: collections.abc
- Python: enum
- Django: using mixins with class based views
- scikit-learn: developing estimators
- Flask-Login
- Qt: meta object compiler, limitations
- C++ Core Guidelines C.135 to C.137
- ISO C++ FAQ: multiple and virtual inheritance
- Itanium C++ ABI
- Eiffel tutorial: inheritance
- Oracle: The Java Language Environment
- C++ history
- Flavors