首页 > 解决方案 > 如何创建类对象的动态列表?

问题描述

在尝试将新元素添加到我的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

标签: pythonlistclassobject

解决方案


这是因为在您的类中,您在类的主体中定义了 x,而不是它的__init__方法。根据文档,这使它成为一个类变量,对于类的所有实例都是一个且相同的变量。


推荐阅读