Skip to content

Instantly share code, notes, and snippets.

@alvinwan
Last active September 14, 2021 02:49
Show Gist options
  • Save alvinwan/ec2b45308f8af742e8c04f2717344131 to your computer and use it in GitHub Desktop.
Save alvinwan/ec2b45308f8af742e8c04f2717344131 to your computer and use it in GitHub Desktop.
Why all Python class constructor should call their parent constructors

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:

  1. When we define A, we treat B as though it was a subclass of C.
  2. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment