Codectionary / Developer documentation / Python

Inheritance & super()

Inheritance lets a class (the child or subclass) reuse and extend the attributes and methods of another class (the parent or superclass), written as class Child(Parent). The built-in super() function gives access to the parent class's methods from within the child, most commonly used to call the parent's __init__ so the child doesn't have to duplicate its setup logic. Python also supports multiple inheritance, where a class inherits from more than one parent.

Syntax

class Child(Parent):\n    def __init__(self):\n        super().__init__()

Examples

Basic Inheritance

A child class automatically gains all methods and attributes of its parent.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    pass  # inherits everything from Animal, adds nothing new

rex = Dog("Rex")
rex.speak()  # Rex makes a sound (inherited method)

Using super()

Calling the parent's __init__ to avoid duplicating setup logic in the child.

class Animal:
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init__(self, name, indoor=True):
        super().__init__(name)  # reuse the parent's setup
        self.indoor = indoor

whiskers = Cat("Whiskers", indoor=True)
print(whiskers.name, whiskers.indoor)  # Whiskers True

Method Overriding

A child class can redefine a method to change its behavior entirely.

class Animal:
    def speak(self):
        print("Some generic animal sound")

class Dog(Animal):
    def speak(self):  # overrides the parent's version
        print("Woof!")

class Cat(Animal):
    def speak(self):
        print("Meow!")

for animal in [Dog(), Cat(), Animal()]:
    animal.speak()

Multiple Inheritance

A class can inherit from more than one parent class at once.

class Swimmer:
    def swim(self):
        print("Swimming")

class Runner:
    def run(self):
        print("Running")

class Triathlete(Swimmer, Runner):
    pass

athlete = Triathlete()
athlete.swim()  # Swimming
athlete.run()   # Running

Best practices

  • Use super().__init__() in a child class's constructor to reuse the parent's setup logic instead of duplicating it
  • Only override a method when the child's behavior genuinely needs to differ from the parent's
  • Favor composition (a class containing an instance of another) over deep inheritance chains when the relationship is not truly "is-a"
  • Use multiple inheritance sparingly - it can introduce ambiguity about which parent a method comes from (Python resolves this via the Method Resolution Order)

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading