Python Tutorial · Object-Oriented Python · Lesson 28 of 42

Python Inheritance

Reuse and extend classes with inheritance, super() and method overriding.

Parent and child classes

A child class inherits all methods and attributes of its parent and can add or override them.

Example 1Try it yourself
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "..."

class Cat(Animal):
    def __init__(self, name, indoor=True):
        super().__init__(name)
        self.indoor = indoor

    def speak(self):
        return f"{self.name} says meow"

tom = Cat("Tom")
print(tom.speak(), tom.indoor)
print(isinstance(tom, Animal))

Output

Tom says meow True
True

super() calls the parent's version of a method — commonly used in __init__.

Polymorphism

Different classes can share a method name, so code can treat them the same way:

Example 2Try it yourself
class Shape:
    def area(self):
        raise NotImplementedError

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side ** 2

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return round(3.14159 * self.r ** 2, 2)

for shape in [Square(3), Circle(1)]:
    print(type(shape).__name__, shape.area())

Output

Square 9
Circle 3.14

Composition over inheritance

Inheritance means "is a". When a class merely uses another ("has a"), store an instance of it instead — composition keeps classes smaller and easier to change.

Test yourself

Which function calls a method from the parent class?

  1. parent()
  2. base()
  3. super()
  4. self.parent()
Show answer

Answer: super()