0
class myObj():
    def __init__(self, pos_i, pos_j, pos_k, n = None, unique_property = []):
        self.pos_i = pos_i
        self.pos_j = pos_j
        self.pos_k = pos_k
        self.unique_property = unique_property

objs = []
count = 0
for i in range(0, 10):
    i_ = []
    for j in range(0, 10):
        j_ = []
        for k in range(0, 10):
            obj = myObj(i, j, k)
            obj.n = count
            j_.append(obj)
            c += 1
        i_.append(j_)
    objs.append(i_)

objs[0][0][0].unique_property.append(1)
print(objs[1][0][0].unique_property) # output: [1]

So as you can see in this code, i have a class myObj, and create a 3D list out of each object (of which they have different properties - their position). After updating the properties of one of the objects in the list, it updates the property of another object in the list.

How do I avoid this and why does this happen?

sidenote: I tried to replicate this, but instead of using objects I used lists. That seemed to dodge the problem, but I don't understand why this occurs with objects, which is the datatype I need to use. Any explanations?

1 Answers1

0

You should not use a mutable object like [] as a default value for a function. Because only one list will be created and shared by all your instances.

You can change your function like this:

class myObj():
    def __init__(self, pos_i, pos_j, pos_k, n = None, unique_property = None):
        self.pos_i = pos_i
        self.pos_j = pos_j
        self.pos_k = pos_k
        self.unique_property = [] if unique_property is None else unique_property
Gelineau
  • 2,031
  • 4
  • 20
  • 30