ProgrammingHardAccenture pattern
What is printed?
What is printed?
class Box:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
def __contains__(self, x):
return x in self.items
b = Box([1, 2, 3])
print(len(b), 2 in b, bool(b))
empty = Box([])
print(bool(empty))- A. 3 True True False
- B. 3 True False False
- C. 3 True True True
- D. TypeError
Correct answer: A. 3 True True False
len(b) uses __len__ (3), and 2 in b uses __contains__ (True). Without a __bool__, Python falls back to __len__ for truthiness: nonzero length is truthy (True for b), and zero length is falsy (False for empty).
More Python Programming questions
- What is printed? python class D: def getitem(self, key): if isinstance(key, slice): return f"slice {key.start}:{key.stop}:{key.step}"…
- What is printed? python try: try: 1 / 0 except ZeroDivisionError: raise RuntimeError("r") except RuntimeError as e: print(e…
- What is printed? python try: raise ValueError("x") from None except ValueError as e: print(e.cause, e.suppresscontext)
- What is printed? python try: try: raise KeyError("k") except ValueError: print("vl") except KeyError: print("kl")
- What is printed? python x = 5 print(f"{x=}")
- What is printed? python print(f"{'hi':>10}|") print(f"{'hi':<10}|") print(f"{'hi':^10}|")