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:
class MyClass:
def __init__(self):
self._items = []
Then _items list object will be different across all class instances
>>> first = MyClass()
>>> first._items.append(1)
>>> second = MyClass()
>>> second._items.append(1)
>>> first._items is second._items
False
and therefore appending will work as expected.