Python creating class instances in a loop
本问题已经有最佳答案,请猛点这里访问。
我刚接触过python,所以我现在很困惑。我只想在一个循环中创建几个类MyClass的实例。
我的代码:
1 2 3 4  | for i in range(1, 10): my_class = MyClass() print"i = %d, items = %d" % (i, my_class.getItemsCount()); my_class.addItem(i)  | 
类Myclass
1 2 3 4 5 6 7 8 9  | class MyClass: __items = [] def addItem(self, item): self.__items.append(item) def getItemsCount(self): return self.__items.__len__();  | 
输出为:
1 2 3 4  | i = 0, items = 0 i = 1, items = 1 i = 2, items = 2 and so on...  | 
但我期望每次迭代时变量my_类中出现my class的新空实例。因此,预期产量为:
1 2 3  | i = 0, items = 0 i = 1, items = 0 i = 2, items = 0  | 
你能帮我理解吗?谢谢。
要解决此问题,可以通过将此代码放入
1 2 3  | class MyClass: def __init__(self): self._items = []  | 
那么,
1 2 3 4 5 6  | >>> first = MyClass() >>> first._items.append(1) >>> second = MyClass() >>> second._items.append(1) >>> first._items is second._items False  | 
因此,附加将按预期工作。
顺便说一句,对于类变量来说,