0
0
Pythonprogramming~20 mins

Why multiple inheritance exists in Python - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Multiple Inheritance Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use multiple inheritance in Python?

Why does Python support multiple inheritance?

ATo prevent any class from inheriting methods or properties.
BTo force a class to have only one parent class to avoid complexity.
CTo make sure classes cannot share any attributes.
DTo allow a class to inherit features from more than one parent class, enabling code reuse and combining behaviors.
Attempts:
2 left
💡 Hint

Think about how combining features from different sources can help in programming.

Predict Output
intermediate
2:00remaining
Output of multiple inheritance example

What is the output of this Python code?

Python
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())
AHello from B
BHello from A
CHello from C
DTypeError
Attempts:
2 left
💡 Hint

Look at the order of inheritance in class C and how Python resolves method calls.

Predict Output
advanced
2:00remaining
Understanding method resolution order (MRO)

What will be printed by this code?

Python
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())
AZ
BX
CY
DTypeError
Attempts:
2 left
💡 Hint

Check the order of classes in A(Y, Z) and how Python chooses methods.

🧠 Conceptual
advanced
2:00remaining
Why might multiple inheritance cause problems?

What is a common problem caused by multiple inheritance?

AIt can cause ambiguity when two parent classes have methods with the same name.
BIt always makes programs run slower.
CIt prevents any code reuse.
DIt disallows creating new classes.
Attempts:
2 left
💡 Hint

Think about what happens if two parents have the same method name.

🚀 Application
expert
3:00remaining
Predict the output with diamond inheritance

What will this code print?

Python
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())
AHello from Left
BHello from Right
CHello from Base
DTypeError
Attempts:
2 left
💡 Hint

Consider the diamond shape of inheritance and Python's MRO.