python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量 。
例1:
class StuCls():
hehe=6#声明类的一个成员变量。想修改它的值为1,需要使用self.hehe = 1或者obj.hehe = 1。
def f(self):
global hehe #声明一个全局变量,与外面的hehe无关系。
hehe=3
print(hehe)
if __name__ == '__main__':
sobj = StuCls()
sobj.f()# 3
print(sobj.hehe)# 6 读的是对像的成员变量值。
print(hehe)# 3 全局变量。
例2:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam) #After local assignment: test spam
do_nonlocal()
print("After nonlocal assignment:", spam) #After nonlocal assignment: nonlocal spam
do_global()
print("After global assignment:", spam) #After global assignment: nonlocal spam
scope_test()
print("In global scope:", spam) #In global scope: global spam
spam = 'jjj'
print("In global scope:", spam) #In global scope: jjj