What is hybrid inheritance in Python?
a) A mix of different types of inheritance
b) Inheritance with only one base class
c) Inheritance with no derived classes
d) Inheritance where classes cannot be instantiated
Answer:
a) A mix of different types of inheritance
Explanation:
Hybrid inheritance in Python is a combination of two or more types of inheritance, such as single, multiple, multilevel, or hierarchical inheritance. It allows for creating complex class hierarchies that can benefit from various inheritance patterns.
class Base:
def greet(self):
print("Hello from Base")
class Derived1(Base):
def greet(self):
print("Hello from Derived1")
class Derived2(Base):
def greet(self):
print("Hello from Derived2")
class Hybrid(Derived1, Derived2):
pass
# Creating an object of Hybrid class
hybrid = Hybrid()
hybrid.greet() # Output depends on method resolution order (MRO)
In this example, the Hybrid
class inherits from both Derived1
and Derived2
, which in turn inherit from Base
. The method resolution order (MRO) determines which method is called when there are multiple inheritance paths.
Hybrid inheritance allows for flexible and powerful class designs, but it can also introduce complexity, so it should be used carefully to avoid confusion and maintainability issues.