Python Inheritance
Inheritance lets one class build on another. The new class — the child or subclass — automatically gets all the attributes and methods of the parent (base class), and can add new ones or change existing ones. It models "is-a" relationships: a Manager is an Employee, a Square is a Shape.
Creating a subclass
Put the parent class in parentheses after the child's name:
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating."
class Cat(Animal):
def meow(self):
return f"{self.name} says meow."
kitty = Cat("Mochi")
print(kitty.eat()) # inherited from Animal
print(kitty.meow()) # defined in Cat
print(isinstance(kitty, Animal))
print(issubclass(Cat, Animal))Mochi is eating.
Mochi says meow.
True
True
Overriding methods
If the child defines a method with the same name as the parent, the child's version wins for objects of the child class:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
class Duck(Animal):
def speak(self):
return "Quack!"
for pet in [Dog("Rex"), Duck("Donald"), Animal("Generic")]:
print(pet.name, "->", pet.speak())Rex -> Woof!
Donald -> Quack!
Generic -> ...
Extending the parent with super()
Often you want to add to the parent's behaviour rather than replace it. super() gives you access to the parent's version of a method. It's especially common in __init__:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def describe(self):
return f"{self.name} earns {self.salary:,}"
class Manager(Employee):
def __init__(self, name, salary, reports):
super().__init__(name, salary) # let the parent set name & salary
self.reports = reports
def describe(self):
base = super().describe()
return f"{base} and manages {len(self.reports)} people"
m = Manager("Thanh", 3_000, ["Ha", "Son"])
print(m.describe())
print(Employee("Ha", 2_000).describe())Thanh earns 3,000 and manages 2 people
Ha earns 2,000
Tip: If a child defines
__init__, the parent's__init__is not called automatically. Forgettingsuper().__init__(...)is a common source of "object has no attribute" errors.
Multi-level inheritance
A child can itself be a parent. Attributes are looked up along the chain:
class Vehicle:
wheels = 0
def info(self):
return f"{type(self).__name__} with {self.wheels} wheels"
class Car(Vehicle):
wheels = 4
class SportsCar(Car):
top_speed = 300
s = SportsCar()
print(s.info())
print(s.top_speed)
print([c.__name__ for c in SportsCar.__mro__])SportsCar with 4 wheels
300
['SportsCar', 'Car', 'Vehicle', 'object']
__mro__ (method resolution order) shows exactly where Python looks, in order. Every class ultimately inherits from object.
Multiple inheritance and mixins
A class can have more than one parent. A popular, safe use is a small mixin class that adds one feature:
import json
class JsonMixin:
def to_json(self):
return json.dumps(self.__dict__)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class JsonPoint(JsonMixin, Point):
pass
p = JsonPoint(2, 5)
print(p.to_json()){"x": 2, "y": 5}
Inheritance vs composition
| Use inheritance when… | Use composition when… |
|---|---|
| the child truly is a kind of parent | the object has a part (a Car has an Engine) |
| it shares most of the parent's behaviour | you only need some of another class's behaviour |
| the hierarchy is shallow (1–2 levels) | you'd need deep or tangled hierarchies |
Composition means storing another object as an attribute (self.engine = Engine()) and delegating to it. Prefer it when in doubt.
Test yourself
How do you declare that Truck inherits from Vehicle?
- class Truck extends Vehicle:
- class Truck(Vehicle):
- class Truck : Vehicle
- class Truck inherits Vehicle:
What does super().__init__(name) do inside a subclass's __init__?
- Creates a second object
- Calls the parent class's __init__ on the same object
- Deletes the parent's attributes
- Makes the class abstract
Which class does every Python class ultimately inherit from?
- base
- type
- object
- Class