首页 > 解决方案 > 有没有办法从 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)

这是我目前正在做的一个模型,但是最后的打印语句打印了最后一个实例的重复,表明所有实例只是最后一个实例的副本。无论如何要避免这种情况?

标签: pythonarraysloopsclassinstance

解决方案


您正在正确地创建类即对象的多个实例。但是,在构造函数中,您设置的是类本身的属性,而不是对象,并且类本身只有一个副本。你要:

class Example:
    def __init__(self,attribute)
        self.attribute=attribute

推荐阅读