理解作用域的原理
当python遇到对变量的引用时,python会在当前函数范围内去查找这个变量是否在函数内有赋值。如果在函数内部无法找到这个变量,python会继续在主函数内查找是否存在该变量。如果有,python就会使用这个变量的值。
举例:
“”“examples of local variables”""
A = ‘This is the text message from main’
def test1():
print(‘in test1.’)
print(A)
print (‘leaving test1.’)
def test2():
print(‘in test2.’)
A = ‘This is the text message from test2.’
print(A)
print (‘leaving test2.’)
def test3():
print (‘in test3.’)
print(A)
A = ‘This is the text message from test3.’
print(’ leaving test3.’)
test1()
test2()
test3()
结果是:
in test1.
This is the text message from main
leaving test1.
in test2.
This is the text message from test2.
leaving test2.
in test3.
Traceback (most recent call last):
File “C:/Users/dearh/AppData/Local/Programs/Python/Python36/exercise/locals.py”, line 23, in
test3()
File “C:/Users/dearh/AppData/Local/Programs/Python/Python36/exercise/locals.py”, line 17, in test3
print(A)
UnboundLocalError: local variable ‘A’ referenced before assignment
test3中A的变量是在输出后定义的,它在test3中先查找了一下,有的。