Understanding instance and class variable python

python

Solution

Class variables are shared between all instances of a class. With immutable types (like int, str, ...) you won't note much of a difference. But consider this:

class MyClass():
    temp = []  
    def myfunc(self, val):
          self.temp.append(val)
          print self.temp

instance1 = MyClass()
instance1.myfunc(1)    # [1]
instance2 = MyClass()
instance2.myfunc(2)    # [1, 2]

In this case both instances share the same list, that is if the instance doesn't have a `temp` member itself, then that of the class is used.

So if you further do:

MyClass.temp.append(3)
print instance1.temp   # [1, 2, 3]
instance1.temp = []
print instance1.temp   # []         uses the instances temp
print instance2.temp   # [1, 2, 3]
del instance1.temp
print instance1.temp   # [1, 2, 3]  uses the class' temp again

Problem

Let's suppose I have 2 classes in different scenario. Scenario 1 ``` class MyClass(): temp = 5 ``` Scenario 2 ``` class MyClass(): temp = 5 def myfunc(self): print self.temp ``` Now when will variable `temp` will be treated as a class variable and instance variable. I am confused because in both the scenarios I am able to access the value of variable `temp` using both. `Object.Temp` (behaving as instance variable) `ClassName.Temp` (behaving as class variable) I believe similar questions have been asked before but it will be a great help if someone can explain this in context of my question.

Original source