LearnFrenzy
Sign in Take a free test

Inheritance and Polymorphism · Predict the Output · Question 3

Method lookup in a diamond Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

What is the output of the following Python program?

main.py
class A:
    def hi(self): return "A"
class B(A):
    def hi(self): return "B"
class C(A):
    def hi(self): return "C"
class D(B, C):
    pass

print(D().hi(), [k.__name__ for k in D.__mro__])
  • A C ['D', 'C', 'B', 'A', 'object']
  • B B ['D', 'B', 'C', 'A', 'object'] Correct
  • C A ['D', 'B', 'A', 'C', 'object']
  • D B ['D', 'B', 'A', 'C', 'object']
Correct Answer: Option B

D has no hi of its own; the first class in the MRO that defines it is B.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links