Why does Python support multiple inheritance?
Think about how combining features from different sources can help in programming.
Multiple inheritance lets a class use methods and properties from multiple parent classes. This helps reuse code and combine different behaviors in one class.
What is the output of this Python code?
class A: def greet(self): return 'Hello from A' class B: def greet(self): return 'Hello from B' class C(A, B): pass obj = C() print(obj.greet())
Look at the order of inheritance in class C and how Python resolves method calls.
Python uses the method resolution order (MRO). Since class A is listed first in C(A, B), its greet method is called.
What will be printed by this code?
class X: def who(self): return 'X' class Y(X): def who(self): return 'Y' class Z(X): def who(self): return 'Z' class A(Y, Z): pass obj = A() print(obj.who())
Check the order of classes in A(Y, Z) and how Python chooses methods.
Python uses MRO and checks Y before Z, so Y's who method is called.
What is a common problem caused by multiple inheritance?
Think about what happens if two parents have the same method name.
Multiple inheritance can cause ambiguity if parent classes have methods with the same name, making it unclear which method to use.
What will this code print?
class Base: def greet(self): return 'Hello from Base' class Left(Base): def greet(self): return 'Hello from Left' class Right(Base): def greet(self): return 'Hello from Right' class Child(Left, Right): pass obj = Child() print(obj.greet())
Consider the diamond shape of inheritance and Python's MRO.
Python uses MRO and checks Left before Right, so Left's greet method is called.