Explain the concept of multiple inheritance and its use in object-oriented programming.
sobes.tech AI
Answer from AI
Multiple inheritance is the ability of a class to inherit properties and methods from more than one base class at the same time. In object-oriented programming, this allows creating more complex and flexible structures by combining the functionality of different classes.
In Python, multiple inheritance is implemented directly, and the method resolution order (MRO) determines which method will be called if it is defined in multiple parent classes.
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() # Will output: Hello from A
Here, class C inherits from A and B, and the greet method is called from class A because it appears first in the inheritance list.
Multiple inheritance is useful when you need to combine the behavior of several classes, but it requires caution to avoid conflicts and ambiguities.