All courses › Intermediate Programming › Inheritance and super()

Inheritance and super()

A class can inherit from another: class Hund(Dyr): makes Hund a subclass of Dyr and gives it access to the parent class's methods. super().__init__() calls the parent's constructor, so the attributes from there are set up correctly.

class B(A):\text{class } B(A):BB inherits all methods and attributes from AA
super().__init__(…)\text{super}().\_\_\text{init}\_\_(\ldots)calls the constructor of the parent class AA

Symbols

AAthe parent class (superclass)
BBthe subclass

Example

class Hund(Dyr):

def __init__(self, navn): super().__init__(navn)

All attributes from Dyr are set up automatically.

Forget super().__init__() and the subclass will be missing the attributes from the parent class.
Practise object orientation for free →

← Classes and __init__ · Encapsulation and polymorphism →

Part of Intermediate Programming: Object orientation.