Reputation: 6424
Is there any difference between a self.var and a var in a class? for example:
class nameClass:
def names(self):
self.name1 = "aaaa"
name2 = "bbbb"
def printNames(self):
print self.name1
print name2
now if I instantiate the class and I want to use the name2 variable, and it doesn't let me.
obj1 = nameClass()
obj.printNames()
it will print the name1 but for the name2 it says:
NameError: global name 'name2' is not defined
so I assume for variables which we use just inside a method it is better to not use 'self' but for other variables that we want to modify later or pass them to the other methods it is better to use 'self'.
Is there any other difference?!
Upvotes: 1
Views: 2051
Reputation: 5289
The name2 = "bbbb"
variable will be only local to a method names
. names will be visible after you set it and to the end of your names
method.
But using the self.name1 = "aaaa"
you will add an attribute to your class instance self, which will be known to other methods of your self
instance.
So use self.xyz
for any data you have to store in your class for longer time and needs to be accessible between methods and use xyz
for temporary variables in single method.
Offtopic: Be careful to initialize every local variable before using it. If you didn't you could have an equally named (global) variable at the lower level and you would use it's value instead and your code will mess up.
Be careful too to not omit the self
when using attributes like name1
, because you could have again global variable name1
and you would read it in your class methods instead.
To demostrate this nasty errors:
def test():
# forgot to initialize constant/variable x
print x
x = 1
test()
class CTest:
def __init__(self):
self.x = 5
def wrongx(self):
print x
t = CTest()
t.wrongx()
The output of this test will be:
1
1
Upvotes: 2
Reputation: 6682
class Foo:
name1 = 'class variable'
def __init__(self):
self.name2 = 'instance variable'
name3 = 'local variable'
def test(self):
print self.name1 # ok
print self.name2 # ok
print name3 # no
Here is a related post: Static class variables in Python
Upvotes: 7