Junior — Middle
How is inheritance from multiple classes simultaneously supported in Python?
sobes.tech AI
Answer from AI
In Python, support for multiple inheritance is implemented directly through specifying multiple base classes when declaring a class.
Syntax:
class DerivedClass(BaseClass1, BaseClass2):
pass
In this case, the DerivedClass inherits attributes and methods from both base classes. If there are methods with the same names in multiple bases, the method resolution order (MRO) determines 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
obj = C()
obj.greet() # Will output: Hello from A
Here, C inherits from A and B, and when calling greet(), the method from A is used because A is listed first and has priority in the MRO.
You can view the MRO using:
print(C.mro())