Inheritance and Polymorphism
You will reuse parent class code and call matching methods on different objects.
Start with a parent class
Inheritance lets a child class reuse a parent class. The child can keep a method, add a method, or replace a method with its own version.
class Parent:
def action(self):
print('Parent action')
class Child(Parent):
pass
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f'{self.name} makes a sound.')
class Dog(Animal):
def speak(self):
print(f'{self.name} says woof!')
def describe(self):
super().speak()
pet = Dog('Milo')
pet.speak()
pet.describe()
Dog.speak() overrides, or replaces, the parent version. Inside describe(), super().speak() calls the parent class method.
Check an object's type
class Animal:
pass
class Cat(Animal):
pass
whiskers = Cat()
print(isinstance(whiskers, Cat))
print(isinstance(whiskers, Animal))
isinstance(object, ClassName) checks whether an object is made from a class or one of its child classes. A Cat is also an Animal.
One method, many object types
class Dog:
def speak(self):
return 'Woof'
class Cat:
def speak(self):
return 'Meow'
class Duck:
def speak(self):
return 'Quack'
animals = [Dog(), Cat(), Duck()]
for animal in animals:
print(animal.speak())
This is polymorphism: the loop uses the same speak() call, while each object responds in its own way. The classes do not need identical internal code.
Key points
- A child class can reuse a parent class.
- Overriding replaces an inherited method.
- super() calls a parent implementation.
- isinstance() recognizes parent-child relationships.
- Polymorphism lets one call work with many objects.
Worked example
Every vehicle honks, but buses charge fare. Bus inherits Vehicle and adds its own twist — code reuse plus specialisation.
class Vehicle:
def describe(self):
return "A vehicle"
class Bus(Vehicle):
def fare(self, km):
return km * 2.5
bus = Bus()
print(bus.describe(), bus.fare(10))
How it works, step by step
- class Bus(Vehicle) means Bus gets everything Vehicle has.
- describe() was never written twice — inheritance supplied it.
- fare() exists only on Bus: specialisation.
References & Further Reading
Related entries from PyLabs's own reference library.
- super() (Access a parent class from inside a child class.)
- isinstance() (Check whether a value is an instance of a type.)
- issubclass() (Check whether one class inherits from another.)
Practice exercise
Not passed yetCreate a parent class Vehicle with a move method that prints Moving. Create a child class Bike that overrides it to print Pedaling. Create a Bike and call move().
# Write your code below
Check yourself
Inheritance and Polymorphism quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.