Motivated by a great student question on Skillshare: https://www.skillshare.com/classes/Learn-How-to-Learn-Coding-Faster-Object-Oriented-Programming-in-Python/563255574/classroom/discussions/287457
We need this when there are multiple classes inheriting from each other. Here's an example: Say we have classes A, B and C. Define B and C, so that there are no parent classes:
class B:
def __init__(self):
print("boo")
class C:
def __init__(self):
print("ciao")
We define A to subclass B and C, like this:
class A(B, C):
def __init__(self):
super().__init__()
print("ayy")
After all this setup, what do you expect to happen when we instantiate class A
? We expect to see ayy
, boo
, and ciao
printed. Here's the problem. If we instantiate A, like this, we see something different:
>>> a = A()
ayy
boo
We notice that "ciao" is never printed! Turns out, the constructor for C is never called, and here's why:
- When we define A, we treat B as though it was a subclass of C.
- B does not call its parent constructor.
As a result, we never see "ciao". This can lead to unexpected behavior, as we expected the constructor to be called to do some setup for the class. To avoid this problem, we always call the parent constructor from the class constructor, even when there's no parent class.