ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class M:
    def __init__(self, v): self.v = v
    def __add__(self, o):
        return M(self.v + (o.v if isinstance(o, M) else o))

ms = [M(1), M(2), M(3)]
print(sum(ms, M(0)).v, end=" ")
try:
    print(sum(ms).v)
except TypeError:
    print("TypeError")
  1. A. 6 6
  2. B. 6 TypeError
  3. C. TypeError
  4. D. 6 0

Correct answer: B. 6 TypeError

sum(ms, M(0)) computes M(0) + M(1) + M(2) + M(3) using M.__add__, giving v = 6. sum(ms) starts from the integer 0, so the first step is 0 + M(1): int.__add__ returns NotImplemented, and M has no __radd__ to fall back on, so TypeError is raised. Adding __radd__ would make the plain sum work.

More Python Programming questions

Exams that ask this topic