Tracing a counting subclass

A programmer extends a simple collection class so that it counts how many items have been added:


Python
class Bag:
    def __init__(self):
        self.items = []

    def add(self, item):
        self.items.append(item)

    def add_all(self, items):
        for item in items:
            self.add(item)

class CountingBag(Bag):
    def __init__(self):
        super().__init__()
        self.added = 0

    def add(self, item):
        self.added += 1
        super().add(item)

    def add_all(self, items):
        self.added += len(items)
        super().add_all(items)

b = CountingBag()
b.add('pen')
b.add_all(['ink', 'nib', 'cap', 'clip'])
print(b.added)


What value does the program print? Give your answer as a whole number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Composition, Inheritance Questions: