python - 如何创建类对象的动态列表?
问题描述
在尝试将新元素添加到我的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
解决方案
这是因为在您的类中,您在类的主体中定义了 x,而不是它的__init__
方法。根据文档,这使它成为一个类变量,对于类的所有实例都是一个且相同的变量。
推荐阅读
- cookies - 新的 SameSite cookie 属性会有效阻止所有定向广告吗?
- html - Bootstrap 中的选项卡式复选框
- javascript-automation - 使用 JXA 获取所有正在运行的全屏应用程序(或空间)的列表
- delphi - 使用 TIdTCPClient 设置 memcashed 值后的 Delphi 慢 readln()
- android - 使用颤动中的手势检测器导航到不同页面时颤动中的黑屏。说多个英雄共享同一个标签
- r - 将 Autoarima 汇总结果放入数据框 R
- java - 来自字符串解析错误的java LocalDateTime
- c# - 列表删除和除外行为不同
- pandas - 合并 2 个 pandas 表并使用它们
- android - 如何在线性布局中对齐按钮(viewpager 点指示器)