Challenge - 5 Problems
Diamond Inheritance Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method call in diamond inheritance
Consider the following Python code using diamond inheritance. What is the output when
obj.greet() is called?Python
class A: def greet(self): return "Hello from A" class B(A): def greet(self): return "Hello from B" class C(A): def greet(self): return "Hello from C" class D(B, C): pass obj = D() print(obj.greet())
Attempts:
2 left
💡 Hint
Remember Python uses Method Resolution Order (MRO) to decide which method to call.
✗ Incorrect
Class D inherits from B and C. Python checks B first in the MRO, so it uses B's greet method.
❓ Predict Output
intermediate2:00remaining
Understanding MRO list in diamond inheritance
What is the output of
print(D.__mro__) for the following classes?Python
class A: pass class B(A): pass class C(A): pass class D(B, C): pass print(D.__mro__)
Attempts:
2 left
💡 Hint
MRO follows the order of inheritance from left to right and then up the hierarchy.
✗ Incorrect
Python's MRO for class D is D, B, C, A, object because B is listed before C in D's inheritance.
❓ Predict Output
advanced2:00remaining
Output with super() in diamond inheritance
What will be printed when
D().greet() is called in this code?Python
class A: def greet(self): return "Hello from A" class B(A): def greet(self): return "B says " + super().greet() class C(A): def greet(self): return "C says " + super().greet() class D(B, C): def greet(self): return "D says " + super().greet() print(D().greet())
Attempts:
2 left
💡 Hint
super() follows the MRO chain calling next method in line.
✗ Incorrect
The call chain is D.greet -> B.greet -> C.greet -> A.greet, concatenating strings in order.
❓ Predict Output
advanced2:00remaining
Effect of changing inheritance order on output
What is the output of
D().greet() if class D inherits as class D(C, B): instead of class D(B, C): in the previous example?Python
class A: def greet(self): return "Hello from A" class B(A): def greet(self): return "B says " + super().greet() class C(A): def greet(self): return "C says " + super().greet() class D(C, B): def greet(self): return "D says " + super().greet() print(D().greet())
Attempts:
2 left
💡 Hint
Changing the order of inheritance changes the MRO and thus the order super() calls methods.
✗ Incorrect
Now the MRO is D, C, B, A, object, so super() calls C.greet then B.greet then A.greet.
🧠 Conceptual
expert2:00remaining
Why Python's diamond problem solution is safe
Why does Python's method resolution order (MRO) prevent the classic diamond problem issues seen in some other languages?
Attempts:
2 left
💡 Hint
Think about how Python orders classes in the MRO list.
✗ Incorrect
Python uses the C3 linearization algorithm to create an MRO that includes each class once, so methods are called only once, avoiding diamond problem issues.