Question 14
Back to Exercise
What is the output of the following Python program?
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!