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))
  1. A. 3 True True False
  2. B. 3 True False False
  3. C. 3 True True True
  4. 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

Exams that ask this topic