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)- A. [1, 2, 3] 1 2 3
- B. [1, 2, 3] 1 2 0
- C. [1] 1 2 0
- 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
- What is printed? python print(1 < 2 < 3, 3 > 2 > 2, 1 == 1 in [1], not 1 == 2, 2 3 2)
- What is printed? python a = [[0] 2] 2 a[0][0] = 1 b = [[0] 2 for in range(2)] b[0][0] = 1 print(a, b)
- What is printed? python def f(n): try: if n == 0: raise ValueError return 10 // (n - 1) except ZeroDivisionError: return -1 except…
- What is printed? python a, b, c = range(5) x, (y, z) = 1, 'hey' print(a, b, c, x, y, z)
- What is printed? python from collections import Counter c = Counter('mississippi') print(c.mostcommon(2), c['z'], sorted(c.items())[:2])
- What is printed? python pts = [(2, 1), (1, 5), (2, 0), (1, 2)] print(sorted(pts, key=lambda p: (-p[0], p[1])), max(pts, key=lambda p: p[1]))