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)- A. [1] [2] [1, 2]
- B. [1, 2] [1, 2] [1, 2]
- C. [1] [2] []
- 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
- What is printed? python def outer(): data = [1, 2, 3] def modify(): data.append(4) modify() return data print(outer())
- What is printed? python a, b = 1, 2 a, b = b, a + b print(a, b)
- What is printed? python from dataclasses import dataclass @dataclass class Point: x: int y: int = 0 p1 = Point(1, 2) p2 = Point(1, 2)…
- What is printed? python x, y = "hello" print(x, y)
- What is printed? python print([x for x in range(20) if x % 2 == 0 if x % 3 == 0])
- What is printed? python print([x if x % 2 == 0 else -x for x in range(5)])