Home > Blockchain >  Should the "self" reference be used for iteration variables in for loops inside classes?
Should the "self" reference be used for iteration variables in for loops inside classes?

Time:03-16

Title pretty much has my full question. For example,

class Test():
    def foobar(self, my_list):
        for element in my_list:
            do_something()

OR

class Test():
    def foobar(self, my_list):
        for self.element in my_list:
            do_something()

What exactly is the difference between the two, with respect to the variable element or self.element?

I think my confusion comes from the fact that my_list is passed to the method, so it is not an instance of Test, therefore self would be inappropriate as element refers to an element of my_list. But the variable element is being created in Test, so every Test instance will have its own element.

CodePudding user response:

The answer is generally "no". The for loop is assigning the variable to point to each element in the list. When it's done, it persists outside the for loop. The better way would be to keep element a local variable, and it will go away when the method ends. But if you assign it to self.element, that's equivalent to self.element = my_list[-1] when the loop ends. Then it will persist when the method exists, and will be accessible from other methods and holders of the class instance. That's usually not what you want.

  • Related