Python Hybrid Inheritance – Examples
Below, are the example of Code Examples of Hybrid Inheritance in Python:
Example 1: Hybrid Inheritance with Platypus Class
In this example, below code shows hybrid inheritance in Python. The Platypus
class inherits from both Mammal
and Bird
classes, showcasing characteristics of both types of animals. This allows Platypus
objects to access methods such as speak()
from Animal
class, give_birth()
from Mammal
class, and lay_eggs
(
)
from Bird
class, reflecting the unique attributes of this hybrid creature.
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal):
def give_birth(self):
print("Mammal gives birth")
class Bird(Animal):
def lay_eggs(self):
print("Bird lays eggs")
class Platypus(Mammal, Bird):
pass
platypus = Platypus()
platypus.speak() # Method from Animal class
platypus.give_birth() # Method from Mammal class
platypus.lay_eggs() # Method from Bird class
Output
Animal speaks Mammal gives birth Bird lays eggs
Example 2: Hybrid Inheritance: Amphibious Vehicles in Python
In this example, AmphibiousVehicle
class showcases hybrid inheritance by inheriting from both Car
and Boat
classes. It inherits characteristics of both types of vehicles, being able to drive like a car and sail like a boat. The method amphibious_action
demonstrates a behavior specific to amphibious vehicles, which can both drive and sail.
class Vehicle:
def move(self):
print("Vehicle moves")
class Car(Vehicle):
def drive(self):
print("Car drives")
class Boat(Vehicle):
def sail(self):
print("Boat sails")
class AmphibiousVehicle(Car, Boat):
def amphibious_action(self):
print("Amphibious vehicle can both drive and sail")
amphibious_vehicle = AmphibiousVehicle()
amphibious_vehicle.move()
amphibious_vehicle.drive()
amphibious_vehicle.sail()
amphibious_vehicle.amphibious_action()
Output
Vehicle moves Car drives Boat sails Amphibious vehicle can both drive and sail
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python.
Hybrid Inheritance is a Type of Inheritance for know more about inheritance Visit.
Contact Us