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)- A. ['x', 'y', 'z'] 0 1 2 False
- B. ['x'] 0 1 2 False
- C. ['x', 'y', 'z'] 0 1 2 True
- 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
- What is printed? python x = 10 class K: x = 20 ys = [x + i for i in range(2)] print(K.ys)
- What is printed? python import itertools data = [1, 1, 2, 1, 1, 1, 3] print([(k, len(list(g))) for k, g in itertools.groupby(data)])…
- What is printed? python class P: def init(self, v): self.v = v def eq(self, o): return self.v == o.v s = set() try: s.add(P(1)) except…
- What is printed? python def make(): n = 0 def inc(): n += 1 return n return inc try: print(make()()) except Exception as e…
- What is printed? python import copy a = [1, 2] b = [a, a] c = copy.deepcopy(b) d = copy.copy(b) c[0].append(3) print(b, c[0] is c[1], d[0]…
- What is printed? python class M: def enter(self): print('in', end=' '); return self def exit(self, t, v, tb): print('exit', t.name if t…