0

I am using the following code to create a list of objects. Each object has an attribute. Each time an object is created, an init method is called to give it initial values, then new values are stored in the attribute.

class Obj():
    a = []

    def init(self):
        for i in range(2):
            self.a.insert(i, 0)


# Main
object_list = []

for i in range(5):
    if i == 0:
        aux = Obj()
        aux.init()    
    else:
        object_list.append(aux)
        aux = Obj()
        aux.init()       

    for j in range(2): 
        aux.a[j] = random.randint(0,50)

for i in range(len(object_list)):
    print object_list[i].a

The expected output would be something like this, where the printed attributes are of length 2:

[21, 9]
[3, 43]
[1, 33]
[5, 12]

However I am getting something like:

[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]
[37, 15, 26, 9, 5, 16, 15, 16, 42, 31]

I know that the problem is that the attribute a of a newly created object points to the attribute a of the previous one, thus I have only one a attribute for all objects.

Why creating a new object does not mean creating a different attribute instead a reference to previous object's attributes?

jchanger
  • 739
  • 10
  • 29

2 Answers2

2

You get this behavior because a = [] makes a a class attribute and not an instance attribute.

If you will create a proper __init__ method and change it to self.a = [] you will get the expected behavior.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

your a = [] is a class attribute and therefore will be shared with all the objects that you create for that class. if you have an __init__ method and you put your a = [] in there like this:

class Obj():
    def __init__(self):
        self.a = []

then you won't have the problem

Halcyon Abraham Ramirez
  • 1,520
  • 1
  • 16
  • 17