Sobes.tech
Junior — Middle

Is it possible to implement multiple inheritance in Python and how does it work?

sobes.tech AI

Answer from AI

In Python, multiple inheritance is supported directly — a class can inherit from multiple base classes, listed separated by commas.

Example:

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

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

class C(A, B):
    pass

obj = C()
obj.method()  # Will output "Method from A"

As seen, class C inherits methods and properties from A and B. When calling a method, Python uses the Method Resolution Order (MRO), which determines the order in which base classes are searched for a method. In this case, it first looks in A, then in B.

Thus, multiple inheritance allows combining behaviors from several classes but requires careful handling to avoid conflicts and ambiguities.