python - 有没有办法从 python 的循环中注册一个类的多个实例?
问题描述
class Example:
def __init__(self,attribute)
Example.attribute=attribute
def function(data): #data in the form of an array
for i in range(len(data)):
instance_storage.append(Example(data[i])
instance_storage=[]
function(some_array)
for instance in instance_storage:
print(instance.attribute)
这是我目前正在做的一个模型,但是最后的打印语句打印了最后一个实例的重复,表明所有实例只是最后一个实例的副本。无论如何要避免这种情况?
解决方案
您正在正确地创建类即对象的多个实例。但是,在构造函数中,您设置的是类本身的属性,而不是对象,并且类本身只有一个副本。你要:
class Example:
def __init__(self,attribute)
self.attribute=attribute
推荐阅读
- ios - 子视图框架不随视图控制器移动
- javascript - setTimeout 的替代方案?
- react-native - “警告:列表中的每个孩子都应该有一个唯一的关键道具”当他们这样做时
- javascript - 防止在使用媒体查询时应用某些 css 元素
- java - QueueChannel如何消费一些费率?
- java - OSGI:Activate 和 Bind 方法在重新启动捆绑包后更改启动顺序
- docker - 如何在 Nexus3 OSS 中找到 Groupid 和 Artifactid?
- javascript - 使用引导菜单在 capybara 中注销
- apache-spark - 如何在 Spark UDF 中设置小数返回类型的精度和小数位数?
- typescript - 通用类型 'Dispatch
' 需要 1 个类型参数。TS2314