ProgrammingModerateProduct-company MCQ pattern
What is printed?
What is printed?
class Bag:
items = []
def add(self, v):
self.items.append(v)
a, b = Bag(), Bag()
a.add(1); b.add(2)
print(a.items, Bag.items is b.items)- A. [1] True
- B. [1, 2] True
- C. [1] False
- D. [1, 2] False
Correct answer: B. [1, 2] True
items is a CLASS attribute, so it is a single list shared by every instance. self.items.append changes it in place (there is no assignment, so no instance attribute is created). Both adds go into the same list.
More Python Programming questions
- What is printed? python class A: def who(self): return "A" class B(A): def who(self): return "B" + super().who() class C(A): def…
- What is printed? python try: try: raise ValueError except TypeError: print("T", end=" ") finally: print("F1", end=" ") except ValueError…
- What is printed? python x = 10 def f(a=x): return a x = 20 print(f())
- What is printed? python print(sum(range(1, 10, 2)), list(range(5))[-1:-4:-1])
- What is printed? python print("abc" < "abd" < "ab", "10" < "9", 10 < 9)
- What is printed? python print({x % 3: x for x in range(7)})