Menu
Inheritance In Python
Inheritance in Python, is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and behaviors from another class. The class that is inherited from is called the "base" or "parent" class, and the class that inherits is called the "derived" or "child" class.
Advantages of Inheritance:
- Code Reusability: Inheritance promotes the reuse of code. The properties and methods of the base class can be reused in the derived class, reducing redundancy.
- Extensibility: New features can be added to a class without modifying existing code. The derived class can extend the functionality of the base class.
- Readability: Inheritance improves code readability by creating a hierarchical structure. Classes that share common attributes and methods are organized in a more logical and intuitive way.
Types of Inheritance in Python:
- Single Inheritance: A class inherits from only one base class.
- Multiple Inheritance: A class inherits from more than one base class.
- Multilevel Inheritance: A class inherits from a base class, and then another class inherits from this derived class.
- Hierarchical Inheritance: Multiple classes inherit from a single base class.
- Hybrid Inheritance: A combination of two or more types of inheritance.
Example in Python:
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} speaks"
# Derived class (Single Inheritance)
class Dog(Animal):
def bark(self):
return f"{self.name} barks"
# Derived class (Multiple Inheritance)
class Bird(Animal):
def fly(self):
return f"{self.name} flies"
# Derived class (Multilevel Inheritance)
class Parrot(Bird):
def sing(self):
return f"{self.name} sings"
# Derived class (Hierarchical Inheritance)
class Cat(Animal):
def meow(self):
return f"{self.name} meows"
# Derived class (Hybrid Inheritance)
class Bat(Bird, Animal):
def echolocate(self):
return f"{self.name} uses echolocation"
# Creating instances
dog_instance = Dog("Buddy")
parrot_instance = Parrot("Polly")
cat_instance = Cat("Whiskers")
bat_instance = Bat("Bruce")
# Output
dog_output = dog_instance.bark()
parrot_output = parrot_instance.fly()
cat_output = cat_instance.meow()
bat_output = bat_instance.echolocate()