global: 在局部访问全局中的内容
nonlocal: 在局部寻找外层函数中离他最近的那个变量
globals() 查看全局中的内容
locals() 查看当前作用域中的内容
1、global的使用:
# 全局变量本身就是不安全的, 不能随意修改, 可以使用闭包 a = 10 def func(): """ :return: global的作用: 1. 可以把全局中的内容引入到函数内部 2. 在全局创建一个变量 """ global a a += 10 print(a) func() print(a)
运行结果为:
20 20
2、nonlocal的使用:
def outer(): a = 10 # 在inner中改变a的值 def inner(): # 寻找外层函数中离他最近的那个变量 nonlocal a a = 20 print(a) print(a) inner() outer()
运行结果:
10 20
3、globals和locals的使用:
def fn(): a = 10 def gn(): b = 20 gn() print(locals()) fn() print(locals()) print(globals())
运行结果:
{'gn': <function fn.<locals>.gn at 0x0000012239A68C80>, 'a': 10} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000012237DCB438>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/learnpj/oldboy/day11/global和nonlocal.py', '__cached__': None, 'i': 10, 'fn': <function fn at 0x0000012237D71E18>} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000012237DCB438>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/learnpj/oldboy/day11/global和nonlocal.py', '__cached__': None, 'i': 10, 'fn': <function fn at 0x0000012237D71E18>}
练习题:
a = 1 def fun_1(): a = 2 def fun_2(): global a a = 3 def fun_3(): a = 4 print(a) print(a) fun_3() print(a) print(a) fun_2() print(a) print(a) fun_1() print(a)
a = 1 def fun_1(): a = 2 def fun_2(): nonlocal a a = 3 def fun_3(): a = 4 print(a) print(a) fun_3() print(a) print(a) fun_2() print(a) print(a) fun_1() print(a)
以上两道练习题的输出结果分别是什么,请自行理解并输出一下!