Tools
Log in
English

Learn to codePython

Python inheritance

Based on Python 3.12

Python inheritance with super(), overriding and the MRO, one line at a time.

In one line

A new class (the child) takes over the attributes and methods of an existing class (the parent) and adds or changes only what is different. You write the parent in parentheses: class Truck(Vehicle):.

Why you need it

If bicycles, trucks and buses all have a name, a wheel count, a distance and drive(), you end up copying the same code into three classes. Fix the distance logic in two of them and forget the third, and the results drift apart.

Keep the shared part once in Vehicle and let each child state only its differences. There is one place to fix.

Everyday picture

Think of a franchise. Head office writes the manual (the parent) for checkout, cleaning and greetings. Each branch (a child) follows it and adds a local dish or two. When head office changes a rule, every branch picks it up at once.

Example code

main.py · 40 lines
class Vehicle:    def __init__(self, name, wheels):        self.name = name        self.wheels = wheels        self.km = 0     def drive(self, km):        self.km += km        return f"{self.name} drove {km}km (total {self.km}km)"     def describe(self):        return f"{self.name} on {self.wheels} wheels"  class Bicycle(Vehicle):    def __init__(self, name):        super().__init__(name, 2)     def ring(self):        return f"{self.name}: ring ring"  class Truck(Vehicle):    def __init__(self, name, load_limit):        super().__init__(name, 6)        self.load_limit = load_limit     def describe(self):        base = super().describe()        return f"{base}, carries up to {self.load_limit}kg"  bike = Bicycle("Pedal")truck = Truck("Hauler", 1000)print(bike.drive(5))print(truck.drive(40))print(bike.describe())print(truck.describe())print(bike.ring())print(isinstance(truck, Vehicle), Truck.__mro__[1].__name__)

When to use it

  • An "is a" sentence sounds right: a truck is a vehicle
  • Several classes share many attributes and methods
  • Each child should do a parent method a little differently (overriding)

If "has a" fits better (a robot has a battery), use composition instead. It comes two topics later.

Python allows several parents (multiple inheritance). Check the lookup order with ClassName.__mro__.

Common mistakes

Leaving out super().__init__() in the child

Once the child writes its own __init__, the parent one no longer runs by itself. name and km never get set, so reading them fails.

Wrong

class Vehicle:    def __init__(self, name):        self.name = name        self.km = 0  class Bicycle(Vehicle):    def __init__(self, name):        self.basket = True  b = Bicycle("Pedal")print(b.name)

When you run itAttributeError: 'Bicycle' object has no attribute 'name'

Fixed

class Vehicle:    def __init__(self, name):        self.name = name        self.km = 0  class Bicycle(Vehicle):    def __init__(self, name):        super().__init__(name)        self.basket = True  b = Bicycle("Pedal")print(b.name)

When you run itPedal

Adding a required parameter to an override

Code that calls it the parent way (v.drive(10)) breaks on the child. Give new parameters a default so the parent-style call still works.

Wrong

class Vehicle:    def drive(self, km):        return km  class Truck(Vehicle):    def drive(self, km, load):        return km * 2 if load else km  for v in [Vehicle(), Truck()]:    print(v.drive(10))

When you run itTypeError: Truck.drive() missing 1 required positional argument: 'load'

Fixed

class Vehicle:    def drive(self, km):        return km  class Truck(Vehicle):    def drive(self, km, load=0):        return km * 2 if load else km  for v in [Vehicle(), Truck()]:    print(v.drive(10))

When you run it10 10

Calling the parent method through the class without self

Vehicle.describe() called on the class has no object to work on. super().describe() passes the current object for you.

Wrong

class Vehicle:    def describe(self):        return "a vehicle"  class Truck(Vehicle):    def describe(self):        return Vehicle.describe() + " that carries cargo"  print(Truck().describe())

When you run itTypeError: Vehicle.describe() missing 1 required positional argument: 'self'

Fixed

class Vehicle:    def describe(self):        return "a vehicle"  class Truck(Vehicle):    def describe(self):        return super().describe() + " that carries cargo"  print(Truck().describe())

When you run ita vehicle that carries cargo

Check yourself

Question 1

What does Truck("Mule", 500).describe() return?

t = Truck("Mule", 500)print(t.describe())

Show the answer

Answer: 2. Mule on 6 wheels, carries up to 500kg The truck's own describe runs. It gets the parent sentence with super().describe() and appends the load limit.

Question 2

When you call bike.describe(), which class does Python search first?

print([c.__name__ for c in Bicycle.__mro__])

Show the answer

Answer: 2. Bicycle The order is Bicycle, then Vehicle, then object. Bicycle has no describe, so the one in Vehicle is used.

Questions people ask

Why use super()?

It calls the parent class method on the current object. The most common case is super().__init__(...) in a child __init__, so the parent sets its values first.

Can a class have several parents?

Yes, as in class C(A, B):. Check the lookup order with C.__mro__; super() follows that order too.

How do I choose between inheritance and composition?

If "a truck is a vehicle" sounds right, inherit. If "a robot has a battery" fits better, use composition.