This question already has an answer here:
I'm new to python, so I'm pretty confused now. I just want to create a couple of instances of class MyClass in a loop.
My code:
for i in range(1, 10):
my_class = MyClass()
print "i = %d, items = %d" % (i, my_class.getItemsCount());
my_class.addItem(i)
Class MyClass
class MyClass:
__items = []
def addItem(self, item):
self.__items.append(item)
def getItemsCount(self):
return self.__items.__len__();
And the output is:
i = 0, items = 0
i = 1, items = 1
i = 2, items = 2
and so on...
But I expect new empty instance of MyClass in variable my_class on each iteration. So expected output is:
i = 0, items = 0
i = 1, items = 0
i = 2, items = 0
Could you help me with understanding? Thanks.
_items
is a class attribute, initialized during the class definition, so by appending values to it, you're modifying the class attribute and not instance attribute.To fight the problem you can create
_items
for each instance of the class by putting this code into__init__
method:Then
_items
list object will be different across all class instancesand therefore appending will work as expected.
Btw, in your case
__items
is not quite good name choice for a class variable.