Junior — Middle
How does the mechanism of multiple inheritance work and what features does it have?
sobes.tech AI
Answer from AI
In Python, multiple inheritance is implemented by specifying multiple base classes when declaring a subclass. This allows the class to inherit attributes and methods from several parent classes.
Features of multiple inheritance in Python:
- The Method Resolution Order (MRO) is used, which determines the order in which methods and attributes are searched in the class hierarchy.
- MRO is based on the C3 linearization algorithm, ensuring predictable and consistent method lookup.
- Conflicts may arise if methods or attributes with the same name are defined in multiple parent classes; MRO helps resolve which method will be called.
Example:
class A:
def greet(self):
print("Hello from A")
class B:
def greet(self):
print("Hello from B")
class C(A, B):
pass
c = C()
c.greet() # Outputs: Hello from A, because A is first in the inheritance list
Thus, multiple inheritance in Python is flexible but requires understanding of MRO for proper use.