0

I made a list containing instances of a class, each of which has an empty list as an attribute. I was trying to append one of those lists on each iteration of my script, and instead all of them got appended. The code looks like this:

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)

Instead of getting one element in each container attribute of all generations every generation has all of the three elements.

zero323
  • 322,348
  • 103
  • 959
  • 935
Boolok
  • 3
  • 2

1 Answers1

1

As described in this question mutable default parameters are stored by reference, so if all instances of your generation type will have a reference to to the same list object. As such, changing one will change it for every other instance.

To fix this, just don’t use an empty list as the default argument, but construct the empty list in the method instead:

class generation:
    def __init__ (self, number, container=None):
        self.n = number
        self.cont = [] if container is None else container
Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602