ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
class V:
    def __init__(self, n): self.n = n
    def __add__(self, o): return V(self.n + o)
    def __radd__(self, o): return V(o * 10 + self.n)
    def __repr__(self): return f"V{self.n}"
print(V(1) + 2, 2 + V(1), sum([V(1), V(2)]))
  1. A. V3 V21 VV12
  2. B. V3 V21 V12
  3. C. V3 V21 V3
  4. D. V3 V21 TypeError

Correct answer: A. V3 V21 VV12

sum starts from 0: 0 + V(1) uses __radd__ and gives V1. Then V1 + V2 calls __add__, which computes 1 + V2; that itself triggers V2.__radd__(1) = V12, and the result is wrapped again as V(V12), whose repr is 'VV12'.

More Python Programming questions

Exams that ask this topic