0

I know the difference of class variable and the instance variable and where they should reside in my code however here is what I'm confused. If for example I have a list of tuples in an instance variable then I use that in a for loop block, would the variables assigned to the values of tuple should have the "self." prefix?

class Asdf():
    cls_var = [(1,2), (3,4)]
    def __init__(self):
        self.ins_var = [(1,2), (3,4)]

    def method(self):
        for (x, y) in self.ins_var: # should it be this way
           Pass
        for (self.x, self.y) in self.ins_var: # or this way to assign variable?
           Pass

Also the same question goes for the class variable but I think it could be without the self. prefix

milinile
  • 15
  • 2
  • 1
    Do you want `x` and `y` to become members of the instance itself, or just local variables of `method`? – Carcigenicate Dec 05 '19 at 16:01
  • Your first way `for x,y in ...` would be normal for any function and is what I would expect to see. The second way needlessly assigns values to `self.x, self.y` which would end up being the last value in your list. Could be confusing that way. – quamrana Dec 05 '19 at 16:01
  • Does this answer your question? [What is the purpose of the word 'self', in Python?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python) – Primusa Dec 05 '19 at 16:01
  • @quamrana actually that was the best explanation I've got. Thanks! I've got a more understanding about that part. – milinile Dec 05 '19 at 19:55

2 Answers2

0

Inside a method you should use the self.variable for variables that you want to persist in the object. They become attributes and can be accessed even after the call of the method has finished.

If the variables are auxiliary for the method, you shouldn't use self.variable. This way, after the call of the method returns, the variables are deleted.

For the class variable, if you don't use self, then you can access the variable without creating an object, that is you can do Asdf.cls_var to get its value. If you want to use self, then you must put the variable inside the __init__ method, and the variable can no longer be accessed without creating an object instance.

Diego Palacios
  • 1,096
  • 6
  • 22
0

Just so you know, the following code demonstrates how both class and instance variables can be accessed from within the class and within an instance:

class Asdf():
    cls_var = [(5,6), (7,8)]
    def __init__(self):
        self.ins_var = [(1,2), (3,4)]

    def printAll(self):
        print(self.ins_var)
        print(self.cls_var)

    @classmethod
    def printCls(cls):
        print(cls.cls_var)
        # print(cls.ins_var)   # This would produce an AttributeError

a = Asdf()
a.printAll()
a.printCls()
Asdf.printCls()

Output:

[(1, 2), (3, 4)]
[(5, 6), (7, 8)]
[(5, 6), (7, 8)]
[(5, 6), (7, 8)]

The output is exactly as you would expect.

quamrana
  • 37,849
  • 12
  • 53
  • 71