当尝试向我的cells
类对象列表添加新元素时,我注意到所有列表值都是添加项的最后一个值。我使用append添加新项目。我怎样才能得到正确的答案?你知道吗
class cells:
x=0
from cells import cells
a=[]
a.append(hucre)
a[0].x=10
a.append(hucre)
a[1].x=20
a.append(hucre)
a[2].x=30
print(a[0].x) #30 where must give me 10
print(a[1].x) #30 where must give me 20
print(a[2].x) #30 where must give me 10
您应该创建类
cells
的新实例,而不是更改cells
的类cells.x
属性。你知道吗因此,应该为类
cells
定义__init__
方法(有关__init__
的详细信息:link,link):将值附加到列表:
创建新对象,否则将更改第一个对象:
……等等。您可以在paren中附加实例化的对象:
这是因为在类中,您在类的主体中定义了x,而不是它的
__init__
方法。这使得它成为一个类变量,对于类的所有实例都是相同的,如the documentation。你知道吗相关问题 更多 >
编程相关推荐