ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Meta:
    shared = []
    def __init__(self, x):
        self.shared.append(x)
m1 = Meta(1)
m2 = Meta(2)
print(m1.shared, m2.shared, Meta.shared)
  1. A. [1] [2] [1, 2]
  2. B. [1, 2] [1, 2] [1, 2]
  3. C. [1] [2] []
  4. D. [1, 2] [1] [1, 2]

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

shared is a class attribute (a single shared list), and self.shared.append(x) mutates that one shared object in place rather than creating per-instance attributes, so both instances and the class itself see the combined [1, 2].

More Python Programming questions

Exams that ask this topic