Sobes.tech
Junior — Middle

What happens if you create a class that inherits from multiple base classes that have the same methods?

sobes.tech AI

Answer from AI

If you create a class in Python that inherits from multiple base classes, and these base classes have methods with the same names, then calling such a method will invoke the method from the first base class in the inheritance list. This is due to the Method Resolution Order (MRO) mechanism.

The MRO determines the order in which base classes are searched when executing a method. To see the order, you can use the __mro__ attribute or the mro() function:

class A:
    def method(self):
        print("A method")

class B:
    def method(self):
        print("B method")

class C(A, B):
    pass

c = C()
 c.method()  # Will print: A method

print(C.__mro__)

In this example, the method from class A will be called because A is first in the inheritance list of class C. If you want to call the method from another base class, you can explicitly refer to it, for example, B.method(self).

What happens if you create a class that inherits from… - sobes.tech