ProgrammingHardTCS NQT · Python · Advanced

What is printed?

What is printed?
class C:
    v = []
    n = 0
    def add(self, x):
        self.v.append(x)
        self.n += 1
a, b = C(), C()
a.add(1); b.add(2); b.add(3)
print(a.v, a.n, b.n, C.n)
  1. A. [1, 2, 3] 1 2 3
  2. B. [1, 2, 3] 1 2 0
  3. C. [1] 1 2 0
  4. D. [1, 2, 3] 3 3 3

Correct answer: B. [1, 2, 3] 1 2 0

The list is a class attribute mutated in place and shared by all instances, but `self.n += 1` reads the class value and creates an instance attribute, leaving C.n at 0.

More Python Programming questions

Exams that ask this topic