We all know how popular Python is as a programming language. Many of the world’s top companies across multiple domains use Python for their applications. Python is an object-oriented programming language with numerous features that make up for its fame, widespread use, and value. Inheritance, an object-oriented feature, is one among them. Implementing inheritance in Python is an exciting task for many developers. But what is inheritance and what are the various types of inheritances in Python?
Let’s discover…
What is Inheritance in Python?
Inheritance refers to obtaining another class’s properties and characteristics (variables and methods). In the hierarchy, the class inheriting another class is termed subclass or child class and the other one is the parent class. Experts have categorized inheritance depending on the hierarchy followed and the number of parent classes and subclasses involved.
So, let’s proceed to look at the five types of inheritances in Python.
Types of Inheritances in Python
Inheritances in Python are of the following five types.
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Let’s look at each inheritance in Python in a little detail.
Single Inheritance
Single inheritance enables a subclass or derived class to inherit properties and characteristics of the parent class. It helps prevent code duplication and enhances its reusability. Here’s an example of a single inheritance code.
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
# Derived class (subclass) inheriting from Animal
class Dog(Animal):
def speak(self):
return f”{self.name} says Woof!”
# Create an instance of the Dog class
dog = Dog(“Buddy”)
# Call the speak method of the Dog class
print(dog.speak()) # Output: Buddy says Woof!
In this example, we have a base class Animal with an __init__ method and a speak method. The Dog class is a derived class that inherits from the Animal class. It overrides the speak method to provide a specific implementation for dogs.
When we create an instance of the Dog class and call its speak method, it returns “Buddy says Woof!” demonstrating single inheritance in Python. The Dog class inherits the attributes and methods of the Animal class and can also provide its own implementations for those methods.
Multiple Inheritance
Does Python support multiple inheritance? Yes. It does. Java classes don’t do that. But Python supports multiple inheritance. In multiple inheritance, a child class inherits from multiple parent classes. It helps when you are required to gather multiple characteristics from various classes. Here’s a code example.
# Base class A
class A:
def method_A(self):
print(“Method A from class A”)
# Base class B
class B:
def method_B(self):
print(“Method B from class B”)
# Derived class C inheriting from both A and B
class C(A, B):
def method_C(self):
print(“Method C from class C”)
# Create an instance of class C
c_instance = C()
# Call methods from class A, B, and C
c_instance.method_A() # Output: Method A from class A
c_instance.method_B() # Output: Method B from class B
c_instance.method_C() # Output: Method C from class C
In this example, we have two base classes, A and B, each with their own methods. The C class is a derived class that inherits from both A and B using multiple inheritance.
When we create an instance of the C class and call its methods, it can access and utilize methods from both base classes A and B, demonstrating multiple inheritance in Python.
Our learners also read: Python Developer Salary [2023]
Multilevel Inheritance
Multilevel inheritance intends to transfer the properties or characteristics to more than one class hierarchically. One can consider it an ancestral to grandchildren relation.
# Base class
class Grandparent:
def __init__(self, name):
self.name = name
def speak(self):
print(f”{self.name} says hello!”)
# Intermediate class inheriting from Grandparent
class Parent(Grandparent):
def introduce(self):
print(f”I am {self.name}, your parent.”)
# Derived class inheriting from Parent
class Child(Parent):
def greet(self):
print(f”Hi, I’m {self.name}, your child.”)
# Create an instance of the Child class
child = Child(“Alice”)
# Call methods from Grandparent, Parent, and Child classes
child.speak() # Output: Alice says hello!
child.introduce() # Output: I am Alice, your parent.
child.greet() # Output: Hi, I’m Alice, your child.
In this example, we have three classes: Grandparent, Parent, and Child. Grandparent is the base class, Parent inherits from Grandparent, and Child inherits from Parent, forming a multilevel inheritance hierarchy.
When we create an instance of the Child class and call its methods, it can access and utilize methods from both its parent classes (Parent and Grandparent), demonstrating multilevel inheritance in Python.
Hierarchical Inheritance
It allows a class to host as a parent class for more than one child class or subclass. The advantages include sharing the functioning of methods with various child classes, thus, helping in preventing the duplication of codes.
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
# Derived class Cat inheriting from Animal
class Cat(Animal):
def speak(self):
return f”{self.name} says Meow!”
# Derived class Dog inheriting from Animal
class Dog(Animal):
def speak(self):
return f”{self.name} says Woof!”
# Create instances of Cat and Dog
cat = Cat(“Whiskers”)
dog = Dog(“Buddy”)
# Call the speak method for Cat and Dog
print(cat.speak()) # Output: Whiskers says Meow!
print(dog.speak()) # Output: Buddy says Woof!
In this example, we have a base class Animal with an __init__ method and a speak method. There are two derived classes, Cat and Dog, each inheriting from the Animal base class. These two classes form a hierarchical inheritance structure.
When we create instances of Cat and Dog and call their speak methods, they provide specific implementations for their respective animals, demonstrating hierarchical inheritance in Python. Both Cat and Dog inherit from the same base class Animal.
Hybrid Inheritance
Hybrid inheritance is a combination of multiple types of inheritance, such as single, multiple, multilevel, and hierarchical inheritance. In Python, you can achieve hybrid inheritance by using a combination of these inheritance types. Here’s an example that demonstrates hybrid inheritance:
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
# Class Mammal inheriting from Animal
class Mammal(Animal):
def speak(self):
return f”{self.name} is a mammal.”
# Class Bird inheriting from Animal
class Bird(Animal):
def speak(self):
return f”{self.name} is a bird.”
# Class Parrot inheriting from Bird and Mammal (multiple inheritance)
class Parrot(Bird, Mammal):
def speak(self):
return f”{self.name} is a parrot and can speak.”
# Create an instance of Parrot
parrot = Parrot(“Polly”)
# Call the speak method for Parrot
print(parrot.speak()) # Output: Polly is a parrot and can speak.
In this example, we have four classes: Animal, Mammal, Bird, and Parrot. The Mammal and Bird classes inherit from the Animal base class, demonstrating hierarchical inheritance. The Parrot class inherits from both Bird and Mammal, showcasing multiple inheritance.
The Parrot class provides its own implementation of the speak method, creating a hybrid inheritance structure. When we create an instance of the Parrot class and call its speak method, it combines features from both Bird and Mammal classes, demonstrating hybrid inheritance in Python.
Kickstart Your Career in Python Development with Ethans!
Are you aspiring to kickstart a rewarding career in the world of software development?
We hope the above explanation helped you overview various types of inheritances in Python. Python, one of the most versatile and widely used programming languages today, could be your gateway to success. Ethans offers meticulously designed, well-curated, and industry-oriented Python course that can help you transform into a skilled and competent Python professional.
To explore our Python course further and receive personalized guidance, contact our counselors at +91 95133 92223 or visit. Your future as a Python professional awaits!
Frequently Asked Questions
Q1: What is Method Overriding in Inheritance?
A: Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in the base class. The overridden method in the subclass takes precedence when called for instances of the subclass.
Q2: When Should I Use Inheritance in Python?
A: Use inheritance when you want to model an “is-a” relationship between classes, and there is a clear hierarchy of objects. Avoid overusing inheritance; prefer composition when a “has-a” relationship is more appropriate.
Q3: How Can I Prevent Method Name Conflicts in Multiple Inheritance?
A: To prevent method name conflicts in multiple inheritance, you can use method resolution order (MRO) or alias methods with unique names in the subclass.
Q4: Are There Any Alternatives to Inheritance in Python?
A: Yes, composition and delegation are alternatives to inheritance. They involve creating objects of other classes within a class to achieve code reuse and flexibility without the constraints of inheritance.
Q5: How Can I Prevent Method Name Conflicts in Multiple Inheritance?
A: To prevent method name conflicts in multiple inheritance, you can use method resolution order (MRO) or alias methods with unique names in the subclass.
Q6: Where Can I Learn More About Python Inheritance?
A: To deepen your understanding of Python inheritance, you can explore a variety of educational resources. Consider enrolling in a reputable IT Training & Placement Institute, to gain structured and expert-guided knowledge. Additionally, reading Python documentation, exploring online tutorials, and referring to books on the subject can provide you with a well-rounded understanding of Python inheritance.