Python Inheritance Example
Python Inheritance Example
Inheritance is a feature in object-oriented programming that allows a class (called a child or derived
and behaviors (methods) from another class (called a parent or base class).
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Inheritance:
Example:
class Animal:
def speak(self):
def bark(self):
print("Dog barks")
d = Dog()
Output:
Dog barks
2. Multiple Inheritance:
In multiple inheritance, a child class inherits from more than one parent class.
Example:
class Animal:
def speak(self):
class Pet:
def type_of_pet(self):
print("This is a pet")
def bark(self):
print("Dog barks")
d = Dog()
Output:
This is a pet
Dog barks
3. Multilevel Inheritance:
Example:
class Animal:
def speak(self):
class Mammal(Animal):
def walk(self):
print("Mammals walk")
class Dog(Mammal):
def bark(self):
print("Dog barks")
d = Dog()
Output:
Mammals walk
Dog barks
4. Hierarchical Inheritance:
Example:
class Animal:
def speak(self):
class Dog(Animal):
def bark(self):
print("Dog barks")
class Cat(Animal):
def meow(self):
print("Cat meows")
d = Dog()
c = Cat()
Output:
Dog barks
Cat meows
5. Hybrid Inheritance:
Example:
class Animal:
def speak(self):
class Pet:
def type_of_pet(self):
print("This is a pet")
class Mammal(Animal):
def walk(self):
print("Mammals walk")
def bark(self):
print("Dog barks")
d = Dog()
Output:
Mammals walk
This is a pet
Dog barks
Summary: