Home > Blockchain >  When looping over objects in a list, why does calling a method of a single object, cause changes to
When looping over objects in a list, why does calling a method of a single object, cause changes to

Time:01-07

In the following code, why does the second and third objects of the list receive the c parameter values even before their own method was called?

class a:
    c = {}
    
    def addC(self, key, error):
        self.c[key] = error

def main():
    i = 0
    aa = []
    while i < 3:
        aa.append(a())
        i  = 1
    for idx, ab in enumerate(aa):
        ab.addC('try', idx)

main()

Here is a visualization of the problem:

Problem visualisation

As shown, for each object in the list, the c parameter after the first for loop iteration looks like this:

{'try': 0}

How can I achieve that the method changes only single objects c parameter value per call, when working in loop? i.e. on the first iteration aa[0].c = {'try', 0}, on the second iteration aa[1].c = {'try', 1}, and on the third iteration aa[2].c = {'try', 2}.

CodePudding user response:

You're using a class variable. If you need the variable C for each object to have its own value, you should use this:

class a:
        def __init__(self):
            self.c = {}  # create instance variable
    
        def addC(self, key, error):
            self.c[key] = error
...
  • Related