ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
class R:
def __init__(self, n): self.n = n
def __len__(self): return self.n
def __getitem__(self, i):
if i >= self.n: raise IndexError
return i * i
r = R(4)
print(list(r), 9 in r, list(reversed(r)), bool(R(0)))- A. TypeError
- B. [0, 1, 4, 9] False [9, 4, 1, 0] False
- C. [0, 1, 4, 9] True [9, 4, 1, 0] True
- D. [0, 1, 4, 9] True [9, 4, 1, 0] False
Correct answer: D. [0, 1, 4, 9] True [9, 4, 1, 0] False
Without __iter__, Python iterates by calling __getitem__ with 0, 1, 2, ... until IndexError, and `in` uses that iteration. reversed() works with __len__ + __getitem__. Truth value falls back to __len__.
More Python Programming questions
- 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…
- What is printed? python class It: def init(self): self.i = 0 def iter(self): return self def next(self): self.i += 1 if self.i > 3: raise…