What is inheritance in Python oops and types of Inheritance?
Inheritance in Python is a way for one class (called the child class or subclass) to gain the properties and behaviors (attributes and methods) of another class (called the parent class or superclass).
This helps in organizing code, reusing it, and building relationships between classes.
Syntax for Inheritance in Python:
To create inheritance, we define a child class that takes the parent class as a parameter in its definition
class Parent:
# Parent class code
class Child(Parent):
# Child class code inherits from Parent
Types of Inheritance in Python:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Let's start them with very understandable definition syntax and examples.
1) Single Inheritance:
A child class inherits from one parent class.
In the single inheritance, when we create an object of the chlid class then we are able to access the properties of the chlid class as well as its parent class.
Example:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof!")
dog = Dog()
dog.speak()
dog.bark()
Output:
Animal sound
Woof!
2) Multiple Inheritance:
A child class inherits from more than one parent class.
in Multiple Inheritance, the child has more than one parent class, so when we create an object of the child class, then we are able to access the properties of child class as well as its all parents class.
Example:
class Father:
def skill(self):
print("Driving")
class Mother:
def hobby(self):
print("Cooking")
class Child(Father, Mother): # Inherits from both Father and Mother
def myself(self):
print("i am a child")
# Usage
child = Child()
child.myself()
child.skill()
child.hobby()
Output:
i am a child
Driving
Cooking
3) Multilevel Inheritance:
A child class inherits from a parent class, which itself is a child of another class.
This is like a chain of classes, every class is inherited from the upper class. When we create an object of our last class then we are able to access the properties of all the upper classes because every class is in the relation of parent child.
Example:
class Vehicle:
def move(self):
print("Moving")
class Car(Vehicle):
def fuel(self):
print("Petrol")
class SportsCar(Car):
def turbo(self):
print("Turbo mode activated!")
sports_car = SportsCar()
sports_car.move()
sports_car.fuel()
sports_car.turbo()
Output:
Moving
Petrol
Turbo mode activated!
4) Hierarchical Inheritance:
Multiple child classes inherit from a single parent class.
Example:
class Bird:
def fly(self):
print( "Flying")
class Sparrow(Bird): # Sparrow inherits from Bird
pass
class Eagle(Bird): # Eagle inherits from Bird
pass
sparrow = Sparrow()
eagle = Eagle()
sparrow.fly()
eagle.fly()
Output:
Flying
Flying
5) Hybrid Inheritance:
A combination of two or more types of inheritance (like multiple and multilevel).
Example:
class Person:
def talk(self):
print("Talking")
class Employee(Person): # Single-level inheritance
def work(self):
print("Working")
class Manager(Employee): # Multilevel inheritance
def manage(self):
print("Managing")
class Freelancer(Person): # Hierarchical inheritance
def freelance(self):
print("Freelancing")
class HybridRole(Manager, Freelancer): # Hybrid inheritance (multiple + multilevel)
pass
# Usage
hybrid = HybridRole()
hybrid.talk()
hybrid.work()
hybrid.manage()
hybrid.freelance()
Output:
Talking
Working
Managing
Freelancing
20+ interview questions on inheritance in Python, complete with answers and examples to help understand each concept
Question 1. What is inheritance in Python? Why is it useful?
Answer: Inheritance is a feature of OOP that allows a class to inherit properties and methods from another class. It helps in reusing code, creating relationships between classes, and making code more maintainable.
Example:
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal): # Dog inherits from Animal
def bark(self):
return "Woof!"
dog = Dog()
print(dog.sound())
print(dog.bark())
Output:
Some sound
Woof!
Question 2. Explain single inheritance with an example.
Answer: In single inheritance, a child class inherits from only one parent class.
Example:
class Vehicle:
def type(self):
return "Vehicle"
class Car(Vehicle): # Car inherits from Vehicle
def wheels(self):
return 4
car = Car()
print(car.type())
print(car.wheels())
Output:
Vehicle
4
Question 3. What is multiple inheritance?
Answer: Multiple inheritance allows a child class to inherit from more than one parent class.
Example:
class Father:
def skill(self):
return "Driving"
class Mother:
def hobby(self):
return "Painting"
class Child(Father, Mother):
pass
child = Child()
print(child.skill())
print(child.hobby())
Output:
Driving
Painting
Question 4. What is multilevel inheritance?
Answer: Multilevel inheritance is when a class inherits from a parent class, which itself inherits from another parent class.
Example:
class Animal:
def live(self):
return "Living"
class Mammal(Animal):
def has_hair(self):
return True
class Dog(Mammal):
def sound(self):
return "Woof!"
dog = Dog()
print(dog.live())
print(dog.has_hair())
print(dog.sound())
Output:
Living
True
Woof!
Question 5. What is hierarchical inheritance?
Answer: In hierarchical inheritance, multiple child classes inherit from the same parent class.
Example:
class Animal:
def sound(self):
return "Animal sound"
class Dog(Animal):
def bark(self):
return "Woof!"
class Cat(Animal):
def meow(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.sound())
print(dog.bark())
print(cat.meow())
Output:
Animal sound
Woof!
Meow!
Question 6. What is hybrid inheritance?
Answer: Hybrid inheritance is a combination of more than one type of inheritance, such as multiple and multilevel inheritance.
Example:
class Person:
def walk(self):
return "Walking"
class Employee(Person):
def work(self):
return "Working"
class Freelancer(Person):
def freelance(self):
return "Freelancing"
class HybridRole(Employee, Freelancer):
pass
hybrid = HybridRole()
print(hybrid.walk())
print(hybrid.work())
print(hybrid.freelance())
Output:
Walking
Working
Freelancing
Question 7. How can you access the parent class’s method from a child class?
Answer: Use super() to access methods of the parent class.
Example:
class Parent:
def greet(self):
return "Hello from Parent"
class Child(Parent):
def greet(self):
return super().greet() + " and Child"
child = Child()
print(child.greet())
Output:
Hello from Parent and Child
Question 8. What is super() and how is it used in inheritance?
Answer: super() returns a temporary object of the superclass and allows you to access its methods and attributes.
Example:
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return super().sound() + " and Woof!"
dog = Dog()
print(dog.sound())
Output:
Some sound and Woof!
Question 9. Can a child class override a method from the parent class?
Answer: Yes, by defining a method with the same name in the child class.
Example:
class Animal:
def sound(self):
return "Animal sound"
class Dog(Animal):
def sound(self):
return "Woof!"
dog = Dog()
print(dog.sound())
Output:
Woof!
Question 10. What is method overriding?
Answer: Method overriding occurs when a subclass provides a specific implementation for a method already defined in its parent class.
Question 11. How does Python handle conflicts in multiple inheritance?
Answer: Python uses the MRO (Method Resolution Order) to determine the order in which to inherit methods and attributes.
Question 12. What is the difference between inheritance and composition?
Answer: Inheritance creates a relationship between classes, while composition involves including objects within other objects to provide functionality.
Question 13. What is the __init__ method’s role in inheritance?
Answer: __init__ initializes class attributes. In inheritance, the child class can inherit the __init__ method or define its own.
Question 14. How can you call a parent class’s __init__ in the child class?
Answer: Using super().__init__().
Question 15. Explain why Python doesn’t support private inheritance.
Answer: Python doesn’t support private inheritance directly as it allows flexibility in accessing attributes and methods.
Question 16. How do isinstance() and issubclass() work with inheritance?
Answer: isinstance() checks if an object is an instance of a class, while issubclass() checks if a class is a subclass of another.
Question 17. Can a class inherit from itself?
Answer: No, self-inheritance would create an infinite loop and is not allowed in Python.
Question 18. How do @classmethod and @staticmethod work with inheritance?
Answer: They allow methods to be called on the class itself and can be inherited by subclasses.
Question 19. What are the advantages of using inheritance?
Answer: Reusability, hierarchy creation, and simplification of complex code are key advantages.
Question 20. Is multiple inheritance considered good practice?
Answer: It depends on the use case; it can lead to complexity if not managed properly, so it’s generally used carefully.
Tags:
Leave a comment
You must be logged in to post a comment.