LearnFrenzy
Sign in Take a free test

Inheritance and Polymorphism · Predict the Output · Question 6

Duck typing with unrelated classes Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Python program?

main.py
class Duck:
    def sound(self): return "Quack"
class Robot:
    def sound(self): return "Beep"
class Stone:
    pass

for thing in [Duck(), Robot(), Stone()]:
    print(getattr(thing, "sound", lambda: "...")(), end=" ")
print()
  • A Quack Beep
  • B AttributeError
  • C Quack Beep None
  • D Quack Beep ... Correct
Correct Answer: Option D

Duck and Robot share no parent, yet both work. getattr with a default supplies a fallback function for Stone.

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