Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为列表中的实例附加实例属性_Python_List_Class_Append - Fatal编程技术网

Python:为列表中的实例附加实例属性

Python:为列表中的实例附加实例属性,python,list,class,append,Python,List,Class,Append,我制作了一个包含类实例的列表,每个类都有一个空列表作为属性。我试图在我的脚本的每次迭代中附加其中一个列表,但是它们都被附加了。代码如下所示: class generation: def __init__ (self, number, container=[]): """This is the class containing lists""" self.n=number self.cont=container class hybrid_v

我制作了一个包含类实例的列表,每个类都有一个空列表作为属性。我试图在我的脚本的每次迭代中附加其中一个列表,但是它们都被附加了。代码如下所示:

class generation:
    def __init__ (self, number, container=[]):
        """This is the class containing lists"""
        self.n=number
        self.cont=container

class hybrid_variant:
    def __init__ (self, generation):
        """Instances of this class go into lists in instances of generation"""
        self.gen=generation

generation_list=[]
for x in range(3):
    hybrid=hybrid_variant(generation= x+1)
    new_generation=True
    for elem in generation_list:
        if elem.n == hybrid.gen:
            new_generation=False
    if new_generation==True:
        generation_list.append(generation(hybrid.gen))
    for elem in generation_list:
        if elem.n == hybrid.gen:
            elem.cont.append(hybrid)
不是在所有代的每个容器属性中获得一个元素,而是每代都具有这三个元素

如中所述,可变默认参数通过引用存储,因此如果
生成的所有实例
类型都引用同一列表对象。因此,每更改一个实例,就会更改另一个实例

要解决此问题,请不要使用空列表作为默认参数,而是在方法中构造空列表:

class generation:
    def __init__ (self, number, container=None):
        self.n = number
        self.cont = [] if container is None else container

您的代码格式已损坏;此外,阅读也很好