Sobes.tech
Junior — Middle

Can you explain the features of multiple inheritance in Python and how it differs from single inheritance?

sobes.tech AI

Answer from AI

Multiple inheritance in Python allows a class to inherit behavior from multiple parent classes simultaneously, unlike single inheritance where a class inherits from only one.

Features of multiple inheritance:

  • Method Resolution Order (MRO) — the order in which methods and attributes are looked up is determined by the C3 linearization algorithm, which helps avoid ambiguities.
  • It enables combining functionalities of different classes, creating more flexible and reusable components.
  • It can lead to complexity and confusion if the inheritance structure is not properly managed.

Example:

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

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

class C(A, B):
    pass

c = C()
c.method()  # Will print "A" according to MRO

In single inheritance, class C could inherit only from A or B, but multiple inheritance allows combining their behaviors.