0

I hava a class like

class Gate():
    def __init__(self, lst):
        self.arr = lst
        self.fill()

    def get_arr(self):
        return self.arr

    def set_arr(self, index1, index2, value):
        self.arr[index1][index2] = value

    def fill(self):
        for i in range(len(self.arr)):
            self.arr[i].append(randrange(2))

I am creating class with "gate_list" attiribute. When creating new object it's adding 1's and 0's to object's list.

Until now every thing is okey. But with object's list also my "gate_list" variable is too changing.

Array = Gate(gate_list)
print(Array.get_arr())
print(gate_list)

Output

[['a', 1], ['b', 0], ['c', 0], ['z', 1], ['d', 1]]
[['a', 1], ['b', 0], ['c', 0], ['z', 1], ['d', 1]]

Where is my fault?

1
  • ... because they are the same list. Commented Dec 19, 2017 at 0:06

1 Answer 1

1

self.arr has a reference to gate_list, which is passed to the constructor. Thus, any mutations of self.arr will also change gate_list. Instead, pass a copy of gate_list to Gate:

import copy

Array = Gate(copy.deepcopy(gate_list))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.