Classes
Inheritance and Super
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
Ninasuper() 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
TrueNotes
- Inheritance models an “is a specialized kind of” relationship.
super()calls the next implementation in the method resolution order.- Prefer composition when an object only needs to use another object.
See also
- related: Classes
- related: Abstract Base Classes
- related: Classmethods and Staticmethods
- next depth: Special Methods
Run the complete example
Expected output
Nina
Nina makes a sound; Nina barks
True
Execution time appears here after you run the example.