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))- A. V(1)
- B. V(2)
- C. V(3)
- 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
- What is printed? python class W: def init(self, x): self.x = x def lt(self, o): return self.x < o.x ws = [W(3), W(1), W(2)] print([w.x for…
- What is printed? python class N: def init(self, v): self.v = v def bool(self): return self.v != 0 n1 = N(0) n2 = N(5) print(bool(n1)…
- What is printed? python class Base: def repr(self): return "Base" class Sub(Base): pass print([Sub(), Sub()])
- What is printed? python class CM3: def enter(self): return 42 def exit(self, et, ev, tb): return False with CM3() as val: print(val)
- What is printed? python from contextlib import contextmanager @contextmanager def cm(): print("setup") yield 1 print("teardown") with cm()…
- What is printed? python class A: def enter(self): print("A enter"); return self def exit(self, a): print("A exit") class B: def…