Multiple Inheritance
suggest changePython uses the C3 linearization algorithm to determine the order in which to resolve class attributes, including methods. This is known as the Method Resolution Order (MRO).
Here’s a simple example:
class Foo(object):
foo = 'attr foo of Foo'
class Bar(object):
foo = 'attr foo of Bar' # we won't see this.
bar = 'attr bar of Bar'
class FooBar(Foo, Bar):
foobar = 'attr foobar of FooBar'
Now if we instantiate FooBar, if we look up the foo attribute, we see that Foo’s attribute is found first
fb = FooBar()
and
>>> fb.foo
'attr foo of Foo'
Here’s the MRO of FooBar:
>>> FooBar.mro()
[<class '__main__.FooBar'>, <class '__main__.Foo'>, <class '__main__.Bar'>, <class 'object'>]
It can be simply stated that Python’s MRO algorithm is
- Depth first (e.g.
FooBarthenFoo) unless - a shared parent (
object) is blocked by a child (Bar) and - no circular relationships allowed.
That is, for example, Bar cannot inherit from FooBar while FooBar inherits from Bar.
For a comprehensive example in Python, see the wikipedia entry.
Another powerful feature in inheritance is super. super can fetch a parent class's features.
If every class defines its own __init__ and the subclass does not call super(), only the __init__ of the first base class runs. Bar is still inherited: an instance of FooBar is also an instance of Bar and of Foo.