0

I have a program (simplified version below) which creates objects in a loop. within that object there is a variable which should be set when the object is created. however, it seams to be storing the values of the previously created objects... for example/

class createList()

    list1 = []

    def __init__(self, int):
        list1.append(int)

for i in range (0, 3)
   x = createList(i)
   print(x.list1)


>>> 0
>>> 0, 1
>>> 0, 1, 2
>>> 0, 1, 2, 3

Can anyone point me in the direction of what I'm, doing wrong?

Chris Headleand
  • 6,003
  • 16
  • 51
  • 69

1 Answers1

1

You've defined list1 as a class variable. Thus it's shared with all instances of createList.

What you want is to define it as an instance variable.

class createList(object):
    def __init__(self, integer):
        self.list1 = []
        self.list1.append(integer)

>>> for i in range(3):
...     x = createList(i)
...     print(x.list1)
...     
... 
[0]
[1]
[2]

Storing a single value in a list sounds a little strange, but it's impossible to say within the context you've given. Also, it's bad practice to overwrite the builtin int.

ps. Technically python doesn't have class or instance variables, it has data attributes. However variables defined in the class statements body are static variables that are shared between each instantiated object. Instance variables are also data attributes but are local to the object in question.

msvalkon
  • 11,887
  • 2
  • 42
  • 38