Lesson 3 of 7 · Classes and Objects · 3 min read · Updated

Inheritance

Building a new class on an existing one, and extending what it does with super().

When one type is a special kind of another — a teacher is a person — the new class can inherit from the existing one. It gets every attribute and method for free, and adds or changes only what is different.

python
class Person:
    def __init__(self, name):
        self.name = name

    def introduce(self):
        return f"I am {self.name}"

class Teacher(Person):
    def __init__(self, name, subject):
        super().__init__(name)
        self.subject = subject

    def introduce(self):
        return f"{super().introduce()} and I teach {self.subject}"

t = Teacher("Lakshmi", "Python")
print(t.introduce())
print(t.name)
print(isinstance(t, Person), isinstance(t, Teacher))
print(issubclass(Teacher, Person))
Output
I am Lakshmi and I teach Python
Lakshmi
True True
True
  • class Teacher(Person): — Teacher is the child (subclass), Person the parent.
  • Defining introduce again in Teacher overrides the parent's version.
  • super() reaches the parent's version, so the child can extend it rather than copy it.
  • A Teacher is also a Person, so isinstance(t, Person) is True.

Warning

If the child defines __init__, the parent's __init__ does not run by itself. Forget super().__init__(name) and the object has no name — the error only appears later, when something reads it.

Note

Every class ultimately inherits from object, which is where default behaviour such as printing as <__main__.Teacher object at 0x...> comes from. Inherit only for a genuine "is a" relationship; a car has an engine, so it should hold one, not inherit from one.

In a child class, what does super().__init__(name) do?

Try this now

  1. Create a Vehicle class with describe(), then Car and Bike subclasses that add a wheel count.
  2. Give BankAccount a SavingsAccount child that adds add_interest(rate).

Create a free account to save your progress, or sign in.