Python在循环中创建类实例 [英] Python creating class instances in a loop
问题描述
我是python的新手,所以现在我很困惑.我只想在一个循环中创建几个MyClass类的实例.
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.
我的代码:
for i in range(1, 10):
my_class = MyClass()
print "i = %d, items = %d" % (i, my_class.getItemsCount());
my_class.addItem(i)
MyClass类
class MyClass:
__items = []
def addItem(self, item):
self.__items.append(item)
def getItemsCount(self):
return self.__items.__len__();
输出为:
i = 0, items = 0
i = 1, items = 1
i = 2, items = 2
and so on...
但是我希望每次迭代都在变量my_class中添加MyClass的新空实例.所以预期的输出是:
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
是一个类属性,在类定义期间进行了初始化,因此通过向其添加值来修改类 >属性和非实例属性.
_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.
要解决此问题,可以通过将以下代码放入__init__
方法中,为该类的每个实例创建_items
:
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 = []
然后_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.
顺便说一句,在您的情况下 <对于类变量,c4>不是很好的名称选择.
Btw, in your case __items
is not quite good name choice for a class variable.
这篇关于Python在循环中创建类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!