Explain it simply
Explain it simply
Just as children inherit eye colour and hair colour from their parents, a child class automatically inherits attributes and methods from its parent class. As soon as you write class Dog(Animal):, Dog objects can use the __init__ and every method written in Animal.
You only rewrite the part that differs in the child class. A dog says "Woof" and a cat says "Meow", so Dog and Cat each override speak() in their own way, while shared work such as storing the name is written once in Animal.
Problem → Why → Solution
The problem: copy-pasted classes drift apart
Before inheritance, suppose Dog and Cat were written by copy-pasting, as below. A bug fix that capitalises the name with title() was made in Dog but forgotten in Cat. The two classes started identical and have now drifted apart, and every new Parrot or Rabbit class makes the problem bigger.
class Dog:
def __init__(self, name):
self.name = name.title() # bug fix applied here...
def describe(self):
return f"{self.name} is a pet."
class Cat:
def __init__(self, name):
self.name = name # ...but forgotten here
def describe(self):
return f"{self.name} is a pet."
print(Cat("kitty").describe()) # kitty is a pet. (not capitalised)Why is this a problem?
When the same logic lives in two places, every change has to be remembered twice, and people forget. With inheritance, __init__ and describe() are written once in an Animal parent and inherited by Dog and Cat, so a single fix reaches every child class at the same moment.
Core concept: overriding, super() and the MRO
class Dog(Animal): makes Animal the parent (base class) and Dog the child (subclass). When you call a method on a Dog object, Python searches the Dog class first, then Animal, and finally the built-in object class. If the child defines a method with the same name as the parent's, that one is found first and hides the parent's version. This is called overriding.
Because of this lookup, a parent method can call a child's method. In the example, Animal.introduce() calls self.speak(), and when self is a Dog it gets Dog.speak(). The parent defines the outline of the job and the child fills in the detail.
When you override, you usually want to extend the parent's work rather than replace it completely. That is what super() is for: super().__init__(name) runs the parent's __init__, which sets self.name. If a child defines __init__ and forgets to call super().__init__(), the parent's attributes are never created and an AttributeError appears later.
Strictly speaking, super() does not call "the parent"; it calls the next class in the MRO (method resolution order). Class.__mro__ shows the order Python searches as a tuple: for Dog it is Dog, Animal, object. With a single parent the two ideas are the same, but with multiple inheritance this order decides which method wins.
Use inheritance only for a genuine is-a relationship: a Dog is an Animal. A Car is not an Engine, it has an Engine, and that has-a relationship calls for composition, where one object is stored as an attribute of another. A quick test helps: if every public method of the parent also makes sense on the child, inheritance fits; if you would have to hide or disable some of them, it does not.
- Call obj.method()
- Search the object's own class first
- Not found: climb the MRO to the parent
- super() jumps to the next class in MRO
The child's method wins, and super() still lets it reach the parent's version.
General pattern
class Parent:
def __init__(self, shared):
self.shared = shared
def action(self):
return "parent behaviour"
class Child(Parent):
def __init__(self, shared, extra):
super().__init__(shared) # parent sets self.shared
self.extra = extra
def action(self): # override
return super().action() + " plus more"class Child(Parent): declares the inheritance. When the child defines __init__, call super().__init__(...) and then add its own attributes. Inside an overriding method, super().action() reuses the parent's version.
Example: Animal, Dog and Bird
Dog replaces speak() completely, while Bird uses super() to reuse and extend the parent's __init__ and speak(). Notice that introduce() is written only in Animal, yet it calls each child's own speak(). The last three lines inspect the hierarchy instead of guessing it.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
def introduce(self):
return f"I am {self.name}. {self.speak()}"
class Dog(Animal):
def speak(self): # override the parent's method
return f"{self.name} says Woof!"
class Bird(Animal):
def __init__(self, name, can_fly=True):
super().__init__(name) # let Animal set self.name
self.can_fly = can_fly
def speak(self):
base = super().speak() # reuse, then extend
return base + (" It flies away." if self.can_fly else " It waddles.")
rex = Dog("Rex")
penguin = Bird("Pingu", can_fly=False)
print(rex.introduce())
print(penguin.introduce())
print(isinstance(rex, Animal), isinstance(rex, Bird))
print(issubclass(Bird, Animal))
print([cls.__name__ for cls in Dog.__mro__])Code breakdown
- Line 9
return f"I am {self.name}. {self.speak()}"Written in Animal, but self.speak() starts its search from self's class, so for a Dog object it calls Dog.speak().
- Line 12
class Dog(Animal):Dog inherits from Animal, so it needs no __init__ of its own; Dog("Rex") uses Animal.__init__.
- Line 19
super().__init__(name)Bird has its own __init__, so Animal.__init__ no longer runs automatically. This line calls it so self.name gets set.
- Line 23
base = super().speak()Takes the parent's "Pingu makes a sound." and appends a sentence that depends on can_fly.
- Line 32
print(isinstance(rex, Animal), isinstance(rex, Bird))Dog is a subclass of Animal, so rex counts as an Animal (True), but it has nothing to do with Bird (False).
- Line 34
print([cls.__name__ for cls in Dog.__mro__])Shows the order Python searches for methods: Dog, Animal, object.
I am Rex. Rex says Woof!
I am Pingu. Pingu makes a sound. It waddles.
True False
True
['Dog', 'Animal', 'object']
Multiple inheritance and the MRO
A Python class can inherit from several parents. If two parents define a method with the same name, the first one found in the MRO wins, which normally follows the left-to-right order inside the class parentheses. Mixins, small classes that each add one feature such as logging or JSON export, rely on this pattern.
class Flyer:
def move(self):
return "flies"
class Swimmer:
def move(self):
return "swims"
class Duck(Flyer, Swimmer):
pass
print(Duck().move()) # flies
print([c.__name__ for c in Duck.__mro__]) # Duck, Flyer, Swimmer, objectComposition instead of inheritance
For a has-a relationship, store the other object as an attribute and delegate to it. If Car keeps an Engine in self.engine instead of inheriting from it, you can swap in an ElectricEngine at runtime, and Car does not inherit a pile of engine methods it never needed.
class Engine:
def start(self):
return "engine started"
class Car:
def __init__(self, engine):
self.engine = engine # Car HAS-AN Engine
def drive(self):
return self.engine.start() + ", car moving"
print(Car(Engine()).drive())In real projects
Where this shows up in real projects
Frameworks use inheritance as an extension point. In Django every model inherits from models.Model and gets methods such as save() and delete() for free. With class-based views you inherit from ListView, override just get_queryset(), and the framework handles pagination and template rendering for you.
The standard library uses it too: custom exceptions inherit from Exception, and unittest tests inherit from unittest.TestCase. Experienced teams still try to keep hierarchies two or three levels deep. If A is inherited by B, B by C and C by D, finding where one of D's methods comes from means opening four files. For parts you want to swap, such as a payment provider or a storage backend, teams choose composition.
Common mistakes
Common mistakes
1. Forgetting to call super().__init__()
Once a child defines __init__, the parent's __init__ no longer runs on its own. Without super().__init__(name), self.name is never created and a later call to introduce() fails with "AttributeError: 'Bird' object has no attribute 'name'". The error appears far from the real mistake, which makes it hard to trace.
2. Misspelling the method you meant to override
Writing def speek(self): in Dog raises no error; it just adds a new method, and rex.speak() keeps returning the parent's "makes a sound". Check the child's output with a test, and if you use a type checker, the typing.override decorator can flag this kind of slip.
3. Modelling has-a with inheritance
class Car(Engine): gives Car every Engine method and produces odd APIs such as car.check_oil_pressure(). If you cannot say "X is a Y" out loud, use composition.
Best practices
Best practices
- A child must work wherever its parent is expected: any function that accepts an Animal should accept a Dog without surprises.
- Keep an overriding method compatible with the parent: same parameters and the same kind of return value, so existing callers keep working.
- Keep hierarchies two or three levels deep; when they grow deeper, rethink the design with composition.
- Call super() with no arguments; the super(Dog, self) form is a leftover from Python 2.
Mini challenge
Mini challenge: Employee and Manager
Write an Employee parent class and a Manager child class. Manager must reuse the parent's pay calculation through super() and add a bonus on top.
- Employee(name, salary) has monthly_pay() (salary / 12, rounded to 2 places) and describe()
- Manager(name, salary, team_size) calls super().__init__()
- Manager.monthly_pay() takes the parent's result via super() and adds 50 per team member
- Manager.describe() appends " and leads N people" to the parent's sentence
class Employee:
def __init__(self, name, salary):
# TODO: store name and yearly salary
pass
def monthly_pay(self):
# TODO: salary / 12 rounded to 2 places
pass
def describe(self):
# TODO: "Hla earns 2000.0 per month"
pass
class Manager(Employee):
def __init__(self, name, salary, team_size):
# TODO: let Employee store name and salary, then keep team_size
pass
# TODO: override monthly_pay() and describe() using super()
# TODO: loop over [Employee("Hla", 24000), Manager("Mya", 36000, 4)]
# and print describe() for each oneExpected: Expected output: Hla earns 2000.0 per month Mya earns 3200.0 per month and leads 4 people True
Show hint
Inside Manager.monthly_pay() you can return super().monthly_pay() + 50 * self.team_size. Manager.describe() reuses the parent's version, which calls self.monthly_pay(), so the amount it shows already includes the bonus.
Show solution
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def monthly_pay(self):
return round(self.salary / 12, 2)
def describe(self):
return f"{self.name} earns {self.monthly_pay()} per month"
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary)
self.team_size = team_size
def monthly_pay(self):
bonus = 50 * self.team_size
return super().monthly_pay() + bonus
def describe(self):
return super().describe() + f" and leads {self.team_size} people"
staff = [Employee("Hla", 24000), Manager("Mya", 36000, 4)]
for person in staff:
print(person.describe())
print(isinstance(staff[1], Employee))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- class Child(Parent): makes the child inherit the parent's attributes and methods.
- A same-named method overrides the parent's, and super() still reaches the parent's version.
- When a child defines __init__, remember to call super().__init__(...).
- Method lookup follows __mro__; choose composition for has-a relationships.
Python Documentation — Classes — Python Software Foundation