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)]))- A. V3 V21 VV12
- B. V3 V21 V12
- C. V3 V21 V3
- 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
- What is printed? python class R: def init(self, n): self.n = n def len(self): return self.n def getitem(self, i): if i >= self.n: raise…
- What is printed? python class C: def init(self): self.d = {} def getattr(self, name): return f"<{name}>" def setattr(self, name, v)…
- What is printed? python class Temp: def init(self): self.c = 0 @property def c(self): return self.c @c.setter def c(self, v): if v < -273…
- What is printed? (Output lines are shown separated by " / ".) python class A: @staticmethod def s(): return "s" @classmethod def c(cls)…
- What is printed? python class Count: total = 0 def init(self): self.total += 1 Count.total += 10 a = Count(); b = Count() print(a.total…
- What is printed? python class Base: def initsubclass(cls, prefix="x", kw): super().initsubclass(kw) cls.tag = prefix + cls.name class…