All lessons
🧬

Inheritance

Extend classes with child classes

Reward
+60 XP

Basic inheritance

A child class inherits attributes and methods from a parent class.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    def speak(self):
        print(f"{self.name} says woof!")

d = Dog("Rex")
d.speak()

super()

Use super() to call the parent class's methods.

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

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

d = Dog("Rex", "Lab")
print(d.name, d.breed)

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • Forgetting to call super().__init__() in the child class.
  • Circular inheritance — a class can't inherit from itself.