ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class V:
    def __init__(self, n, log): self.n, self.log = n, log
    def __add__(self, o): self.log.append("add"); return V(self.n + getattr(o, "n", o), self.log)
    def __radd__(self, o): self.log.append("radd"); return V(self.n + o, self.log)
    def __iadd__(self, o): self.log.append("iadd"); self.n += getattr(o, "n", o); return self
log = []
a = V(1, log); b = a
a += 2
a = a + a
b = 5 + b
s = sum([a, b])
print(a.n, b.n, s.n, " ".join(log))
  1. A. 6 6 12 iadd add radd add
  2. B. 6 8 14 iadd add radd add add
  3. C. 6 11 17 iadd add radd radd add
  4. D. 6 8 14 iadd add radd radd add

Correct answer: D. 6 8 14 iadd add radd radd add

a += 2 uses __iadd__, mutating the shared object to 3 (b sees it). a = a + a creates a NEW V(6); b still refers to the old V(3). 5 + b: int.__add__ returns NotImplemented, so Python tries b.__radd__(5) → V(8). sum starts from the int 0, so its first step 0 + a is another __radd__, and the second step V + V is __add__: 6 + 8 = 14. Log: iadd add radd radd add. Forgetting sum's implicit start value 0 loses the second radd.

More Python Programming questions

Exams that ask this topic