What is the difference between creating a variable using the self.variable syntax and creating one without?
I was testing it out and I can still access both from an instance:
class TestClass(object):
j = 10
def __init__(self):
self.i = 20
if __name__ == '__main__':
testInstance = TestClass()
print testInstance.i
print testInstance.j
However, if I swap the location of the self, it results in an error.
class TestClass(object):
self.j = 10
def __init__(self):
i = 20
if __name__ == '__main__':
testInstance = TestClass()
print testInstance.i
print testInstance.j
>>NameError: name 'self' is not defined
So I gather that self has a special role in initialization.. but, I just don’t quite get what it is.
selfrefers to the current instance of the class. If you declare a variable outside of a function body, you’re referring to the class itself, not an instance, and thus all instances of the class will share the same value for that attribute.In addition, variables declared as part of the class (rather than part of an instance) can be accessed as part of the class itself:
Since this value is class-wide, not only can you read it directly from the class:
But it will also change the value for every instance of the class:
Note, however, that this is only the case if you don’t override a class variable with an instance variable. For instance, if you created the following:
and then did the following:
Then you’d get the following results:
As noted in the comments, assigning to
two.acreates an instance-local entry on that instance, which overrides theafromBar, hence whyBar.ais still 1 buttwo.ais 3.