Inheritance Examples in Python
Single Inheritance
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Animal makes a sound"
# Child class inheriting from Animal
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
# Creating an object of Dog class
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy says Woof!
Multiple Inheritance
# Parent class 1
class Bird:
def fly(self):
return "I can fly!"
# Parent class 2
class Fish:
def swim(self):
return "I can swim!"
# Child class inheriting from both Bird and Fish
class Duck(Bird, Fish):
def quack(self):
return "Quack! Quack!"
# Creating an object of Duck class
duck = Duck()
print(duck.fly()) # Output: I can fly!
print(duck.swim()) # Output: I can swim!
print(duck.quack()) # Output: Quack! Quack!
Multilevel Inheritance
# Base class
class Vehicle:
def info(self):
return "This is a vehicle"
# Derived class from Vehicle
class Car(Vehicle):
def car_info(self):
return "This is a car"
# Derived class from Car
class ElectricCar(Car):
def battery_info(self):
return "This car runs on electricity"
# Creating an object of ElectricCar class
tesla = ElectricCar()
print(tesla.info()) # Output: This is a vehicle
print(tesla.car_info()) # Output: This is a car
print(tesla.battery_info()) # Output: This car runs on electricity
Hierarchical Inheritance
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some generic animal sound"
# Child class 1
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
# Child class 2
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Child class 3
class Cow(Animal):
def speak(self):
return f"{self.name} says Moo!"
# Creating objects of different child classes
dog = Dog("Buddy")
cat = Cat("Whiskers")
cow = Cow("Daisy")
# Calling the speak method
print(dog.speak()) # Output: Buddy says Woof!
print(cat.speak()) # Output: Whiskers says Meow!
print(cow.speak()) # Output: Daisy says Moo!