LearnFrenzy
Sign in Take a free test

Inheritance and Polymorphism · Predict the Output · Question 14

sum() of custom objects with __radd__ Answer, explanation & discussion

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

What is the output of the following Python program?

main.py
class Pts:
    def __init__(self, n): self.n = n
    def __add__(self, other):
        return Pts(self.n + (other.n if isinstance(other, Pts) else other))
    __radd__ = __add__
    def __repr__(self): return f"Pts({self.n})"

print(sum([Pts(5), Pts(7), Pts(3)]), Pts(1) + 4, 4 + Pts(1))
  • A TypeError
  • B Pts(15) Pts(5) 5
  • C Pts(15) Pts(5) Pts(5) Correct
  • D 15 Pts(5) Pts(5)
Correct Answer: Option C

sum starts with 0 + Pts(5), handled by __radd__; 4 + Pts(1) works the same way.

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