• recategorized by
82 views
1 1 vote

Consider the following Python code:

class Counter:
    count = []

    def __init__(self, value):
        self.value = value

    def add(self):
        self.count.append(self.value)
        self.value += 1
        return self.count

a = Counter(1)
b = Counter(5)

r1 = a.add()
b.count = b.count[:]
r2 = b.add()
r3 = a.add()

print(r1, r2, r3, Counter.count)

What is the output of the code above?

  1. [1] [5] [2] [1, 2]
  2. [1, 2] [1, 5] [1, 2] [1, 2]
  3. [1, 5, 2] [1, 5, 2] [1, 5, 2] [1, 5, 2]
  4. [1, 5] [1, 5] [1, 2] [1, 5]

1 Answer

1 1 vote

The variable $\texttt{count}$ is a class variable, so it is shared by objects unless an object gets its own instance variable with the same name.

First, $\texttt{a.add()}$ appends $\texttt{1}$ to the shared class list.

Counter.count = [1]

So $\texttt{r1}$ refers to the same class list.

The statement $\texttt{b.count = b.count[:]}$ first reads the class list $\texttt{[1]}$, copies it, and then stores that copy as an instance variable of $\texttt{b}$.

Now $\texttt{b}$ has its own separate $\texttt{count}$ list.

Then $\texttt{b.add()}$ appends $\texttt{5}$ to only $\texttt{b.count}$.

b.count = [1, 5]

Then $\texttt{a.add()}$ appends $\texttt{2}$ to the original class list.

Counter.count = [1, 2]

Since $\texttt{r1}$ and $\texttt{r3}$ refer to the class list, both show $\texttt{[1, 2]}$.

Therefore, the output is:

[1, 2] [1, 5] [1, 2] [1, 2]

Correct Option: B

Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
83
83 views
GO Classes asked Jun 6
83 views
Consider the following Python code:def make_funcs(): funcs = [] total = 0 for i in range(3): def add(x, step=i): nonlocal total total += x + step return total funcs.appen...
0 0 votes
1 1 answer
106
106 views
GO Classes asked Jun 6
106 views
Consider the following Python code:def evaluate(x): try: if x == 0: return "zero" return "value" finally: x += 1 if x == 1: return "changed" print(evaluate(0), evaluate(2...
0 0 votes
1 1 answer
80
80 views
GO Classes asked Jun 6
80 views
Consider the following Python code:nums = [1, 2, 3] it = iter(nums) first = next(it) nums.append(4) second = list(it) nums.append(5) third = list(it) print(first, second,...
0 0 votes
1 1 answer
94
94 views
GO Classes asked Jun 6
94 views
Consider the following Python code:data = {"a": , "b": } x = data.setdefault("c", data["a"]) x.append(3) data["a"].append(4) data["b"] = data["a"][:] data["b"].append(5...