Some code and descriptions:
# name_space.py class Class1(object): var1 = 11 def f1(self): print Class1.var1 # this will OK print var1 # this will be an error def func_1(): var1 = 11 def func_2(): print var1 # here will be OK func_2() So, as we can see:
- Define a function in a class, the inner function doesn't have the ability to access the variables directly in the outer class. (We can still access the variables with the class name).
- Define a function in a function, the inner function has the ability to access the variables directly in the outer function.
More codes:
# name_space2.py class A(object): def f1(self): def f2(): print f1 # this will be an error print A.f1 # this will OK f2() So, why python use different scope mechanisms in function and class?
print Class1.var1 # this will OKwe'd rather seeprint self.var1. You're entirely new to python aren't you ?