ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class V:
    def __init__(self, x):
        self.x = x
    def __add__(self, o):
        return V(self.x + o.x)
    def __repr__(self):
        return f"V({self.x})"
print(V(1) + V(2))
  1. A. V(1)
  2. B. V(2)
  3. C. V(3)
  4. D. 3

Correct answer: C. V(3)

V(1) + V(2) invokes __add__, which returns a new V with x = 1 + 2 = 3; printing it uses __repr__, giving V(3).

More Python Programming questions

Exams that ask this topic