I’m having a problem understanding how class / instance variables work in Python. I don’t understand why when I try this code the list variable seems to be a class variable
class testClass():
list = []
def __init__(self):
self.list.append('thing')
p = testClass()
print p.list
f = testClass()
print f.list
Output:
['thing']
['thing', 'thing']
and when I do this it seems to be an instance variable
class testClass():
def __init__(self):
self.list = []
self.list.append('thing')
p = testClass()
print p.list
f = testClass()
print f.list
Output:
['thing']
['thing']
This is because of the way Python resolves names with the
.. When you writeself.listthe Python runtime tries to resolve thelistname first by looking for it in the instance object, and if it is not found there, then in the class instance.Let’s look into it step by step
listname into the objectself?listname into the class instance of objectself?But when you bind a name things are different:
listname into the objectself?So, that is always an instance variable.
Your first example creates a
listinto the class instance, as this is the active scope at the time (noselfanywhere). But your second example creates alistexplicitly in the scope ofself.More interesting would be the example:
That will print:
The moment you delete the instance name the class name is visible through the
selfreference.