Python Inheritance
Inheritance lets a new class take over everything from an existing class and then add or change what it needs. The existing class is the parent (or base class), and the new one is the child (or subclass). A Car and a Bike are both vehicles: they share a brand, a speed and a way to describe themselves, and each adds its own details. Inheritance avoids writing the shared parts twice.
A parent and a child class
The parent goes in brackets after the child's name. The child inherits all the parent's attributes and methods:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def describe(self):
return f"{self.name} says {self.speak()}"
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for pet in [Dog("Rex"), Cat("Tom"), Animal("Fish")]:
print(pet.describe())Rex says Woof Tom says Meow Fish says ...
Dog and Cat override speak with their own version. describe is written only once, in Animal, but it calls whichever speak belongs to the actual object.
Extending the constructor with super()
When a child needs extra attributes, it defines its own __init__ and calls the parent's constructor with super(), so the shared setup is not repeated:
class Vehicle:
def __init__(self, brand, wheels):
self.brand = brand
self.wheels = wheels
def info(self):
return f"{self.brand} with {self.wheels} wheels"
class Car(Vehicle):
def __init__(self, brand, seats):
super().__init__(brand, 4)
self.seats = seats
def info(self):
return super().info() + f" and {self.seats} seats"
print(Vehicle("Hero", 2).info())
print(Car("Tata", 5).info())Hero with 2 wheels Tata with 4 wheels and 5 seats
super().info() runs the parent's version of the method, and the child adds to its result. This is the usual way to extend behaviour rather than replace it completely.
Checking types
isinstance(obj, Class) is true for objects of the class and of its children; issubclass checks the relation between two classes:
class Animal: pass
class Dog(Animal): pass
rex = Dog()
print(isinstance(rex, Dog), isinstance(rex, Animal), isinstance(rex, str))
print(issubclass(Dog, Animal), issubclass(Animal, Dog))
print(Dog.__bases__[0].__name__)True True False True False Animal
Every class has a parent
A class without a parent in brackets inherits from object, Python's root class, which provides basic methods such as __str__ and __eq__. A class can even have several parents, called multiple inheritance, but use that sparingly: deep or tangled family trees make code hard to follow. Prefer inheritance when the child truly is a kind of the parent.
Practice exercises
- Write a class
Shapewith a methodareareturning 0, and childrenSquareandCirclethat override it. - Print the area of a list of mixed shapes in one loop.
- Write
Employeewith a name and salary, andManager(Employee)that adds a team list and usessuper().__init__. - Check with
isinstancewhich of your objects are shapes.