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.
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:
In this case both instances share the same list, that is if the instance doesn’t have a
tempmember itself, then that of the class is used.So if you further do: