What is hierarchical inheritance in Python?

What is hierarchical inheritance in Python?

a) Multiple classes inheriting from the same base class
b) One class inheriting from multiple base classes
c) A class that inherits from a child class
d) A base class with no derived classes

Answer:

a) Multiple classes inheriting from the same base class

Explanation:

Hierarchical inheritance in Python occurs when multiple classes inherit from the same base class. This allows the derived classes to share the common attributes and methods of the base class while also having their own specific implementations.

class Parent:
def greet(self):
print("Hello from Parent")

class Child1(Parent):
def greet(self):
print("Hello from Child1")

class Child2(Parent):
def greet(self):
print("Hello from Child2")

# Creating objects of Child1 and Child2 classes
child1 = Child1()
child2 = Child2()
child1.greet()  # Output: Hello from Child1
child2.greet()  # Output: Hello from Child2

In this example, both Child1 and Child2 inherit from the Parent class. They share the greet() method from the Parent class but can override it to provide their own specific behavior.

Hierarchical inheritance is useful when you want to create multiple classes that share a common structure but also have their own unique characteristics.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top