How does Python support multiple inheritance?
Answer:
Explanation:
Python supports multiple inheritance, where a class can inherit from more than one parent class. This allows the child class to access attributes and methods from all its parent classes. Python resolves potential conflicts between parent classes using the Method Resolution Order (MRO), which determines the order in which base classes are searched when executing a method.
class Base1:
def greet(self):
print("Hello from Base1")
class Base2:
def greet(self):
print("Hello from Base2")
class Derived(Base1, Base2):
pass
# Creating an object of the Derived class
derived = Derived()
derived.greet() # Output: Hello from Base1 (based on MRO)
In this example, the Derived
class inherits from both Base1
and Base2
. The MRO determines that the method from Base1
is executed first. Multiple inheritance allows for more complex and flexible class designs but should be used carefully to avoid conflicts and maintain readability.
Understanding how Python handles multiple inheritance is crucial for creating classes that combine functionality from multiple sources while maintaining clear and predictable behavior.