In Python, invoke super as: Where’s self? Or the MRO? – At compile time, Python adds a __class__ closure cell.– At runtime, super() grabs self from the calling frame — and walks type(self).__mro__ from __class__. No arguments needed (unlike Python 2)!
Some Python rules for inheritance: – Use super().x() to find the next class with a method “x”– “Next” is defined on the instance, aka type(self).__mro__– Every ancestor class should also use super().x()– This allows multiple parents’ x() methods to run
Python class C inherits from (A, B), and both A.__init__ and B.__init__ invoke super().__init__(). We run C(). It prints “B, A”. How does B.__init__ run? A doesn’t inherit from B. The answer: super() looks at the MRO of C, not A. B isn’t in A.__mro__. But it is in C.__mro__.
Multiple inheritance in Python? Make sure all parents run super():
In a Python child class with two parents, which __init__ runs?
Does Python allow for multiple inheritance? Yes: And so: C.__bases__ returns: (<class ‘__main__.A’>, <class ‘__main__.B’>)
In Python, super() searches the MRO until it finds a match:
Didn’t call super() __init__ in your Python class? Attributes normally set on the parent won’t be on the child!
The most common place we use super() in Python? __init__:
Misspelled the method you invoke via super() in a Python method? It’s a runtime error: We get: AttributeError: ‘super’ object has no attribute ‘y’