Editor

Python Program to Show Inheritance

Intermediate · Classes and objects

Inheritance lets a new class, the child or subclass, reuse the attributes and methods of an existing class, the parent or base class, and add or change only what is different. This program has an Animal parent class and two child classes, Dog and Bird, that share its code but make their own sounds.

Program

inheritance_example.py
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
def describe(self):
print(f"{self.name} has {self.legs} legs")
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal): # Dog inherits everything from Animal
def speak(self): # and replaces speak() with its own version
print(f"{self.name} says Woof!")
class Bird(Animal):
def __init__(self, name, can_fly):
super().__init__(name, 2) # let Animal set the name and the legs
self.can_fly = can_fly
def speak(self):
print(f"{self.name} says Tweet!")
pets = [Animal("Some animal", 4), Dog("Bruno", 4), Bird("Mithu", True)]
for pet in pets:
pet.describe()
pet.speak()
print("Is Bruno an Animal?", isinstance(pets[1], Animal))
print("Can Mithu fly?", pets[2].can_fly)
Output
Some animal has 4 legs
Some animal makes a sound
Bruno has 4 legs
Bruno says Woof!
Mithu has 2 legs
Mithu says Tweet!
Is Bruno an Animal? True
Can Mithu fly? True

How it works

  1. class Dog(Animal): makes Dog a child of Animal, so a dog gets __init__, describe() and speak() without writing them again.
  2. Dog defines its own speak(), which replaces the parent's version for dogs only; this is called method overriding.
  3. Bird adds a new attribute, so its __init__ first calls super().__init__(name, 2) to let Animal set the name and the two legs.
  4. The loop calls the same two methods on every pet, and each object runs its own version, which is called polymorphism.
  5. One parent with several children, as here, is called hierarchical inheritance, and isinstance() confirms that a dog is also an animal.

Other ways to write it

Multilevel inheritance

Multilevel inheritance
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi, I am {self.name}"
class Student(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
def greet(self):
return super().greet() + f" from {self.school}"
class Prefect(Student):
def greet(self):
return super().greet() + ", and I am a prefect"
for p in [Person("Ravi"), Student("Meera", "DPS"), Prefect("Asha", "KV Delhi")]:
print(p.greet())
Output
Hi, I am Ravi
Hi, I am Meera from DPS
Hi, I am Asha from KV Delhi, and I am a prefect

Each class builds on its parent's greet() by calling super().greet(), so a Prefect gets the text from all three levels. A chain like this is called multilevel inheritance.

Multiple inheritance

Multiple inheritance
class Swimmer:
def swim(self):
return "can swim"
class Flyer:
def fly(self):
return "can fly"
class Duck(Swimmer, Flyer): # two parents
pass
d = Duck()
print("A duck", d.swim(), "and", d.fly())
print("Parents of Duck:", [c.__name__ for c in Duck.__bases__])
Output
A duck can swim and can fly
Parents of Duck: ['Swimmer', 'Flyer']

A class can inherit from more than one parent, and it gets the methods of all of them. pass means the class adds nothing of its own.

Try it yourself

Add a Cat class that inherits from Animal and says "Meow!", then add a cat to the pets list.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises