Classes

Inheritance and Super

Inheritance reuses behavior, and super delegates to a parent implementation.

A child class names its parent in parentheses. Dog instances get the Animal.__init__ method because Dog does not define its own initializer.

Source

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

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

class Dog(Animal):
    def speak(self):
        base = super().speak()
        return f"{base}; {self.name} barks"

pet = Dog("Nina")
print(pet.name)

Output

Nina
ABCDMRODBCAobject
Multiple inheritance forms a graph; C3 linearisation flattens it into the MRO Python uses for attribute lookup.

super() delegates to the parent implementation. The child method can reuse the parent result and then add specialized behavior.

Source

print(pet.speak())
print(isinstance(pet, Animal))

Output

Nina makes a sound; Nina barks
True

Notes

See also

Run the complete example

Example code

Expected output

Nina
Nina makes a sound; Nina barks
True

Execution time appears here after you run the example.