CS FundamentalsVery hardProduct-company design interview

This code illustrates the 'fragile base class' problem. What does it print?

This code illustrates the 'fragile base class' problem. What does it print?
class Bag:
    def __init__(self): self.items = []
    def add(self, x): self.items.append(x)
    def add_all(self, xs):
        for x in xs: self.add(x)
class CountingBag(Bag):
    def __init__(self):
        super().__init__(); self.count = 0
    def add(self, x):
        self.count += 1; super().add(x)
    def add_all(self, xs):
        self.count += len(xs); super().add_all(xs)
b = CountingBag()
b.add_all([1, 2, 3])
b.add(4)
print(b.count, len(b.items))
  1. A. 4 4
  2. B. 7 4
  3. C. 7 7
  4. D. 3 4

Correct answer: B. 7 4

add_all adds 3 to count, then the base add_all calls self.add, which is the overridden add, adding 1 per item: 6, plus 1 for add(4) = 7. The subclass depends on a hidden implementation detail of the base, which is why composition is often safer.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic