ProgrammingVery hardPython · GATE DA · Advanced

What is printed?

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

Correct answer: C. ['x', 'y', 'z'] 0 1 2 True

self.items += [v] calls list.__iadd__ in place on the shared class list and then rebinds the instance attribute to the same object; for the int, += creates a new instance attribute n, leaving Tag.n at 0.

More Python Programming questions

Exams that ask this topic