#nonlocal
用来声明外层的局部变量。
#global
用来声明全局变量。
#测试nonlocal,global关键字的用法
a = 100
def outer():
b = 10
def inner():
nonlocal b #声明外部函数的局部变量
print("inner:",b)
b = 20
inner()
print("outer:",b)
global a #声明全局变量
a = 1000
print("inner:",a)
outer()
结果:nonlocal改变的外部函数outer中b的值。
inner: 10
outer: 20
inner: 1000
Process finished with exit code 0
#测试LEGB
Python 在查找“名称”时,是按照 LEGB 规则查找的:
Local-->Enclosed-->Global-->Built in
Local 指的就是函数或者类的方法内部
Enclosed 指的是嵌套函数(一个函数包裹另一个函数,闭包)
Global 指的是模块中的全局变量
Built in 指的是 Python为自己保留的特殊名称。
# str = "global str"
def outer():
# str = "outer"
def inner():
str = "inner" #定义在函数内部的str
print(str)
inner()
outer()
输出: inner
str = "global str"
def outer():
# str = "outer"
def inner():
# str = "inner"
print(str)
inner()
outer()
输出:global str
# str = "global str"
def outer():
# str = "outer"
def inner():
# str = "inner"
print(str)
inner()
outer()
分析:现在函数内部、嵌套函数内及全局变量中均不含str,则找python自身的保留字str
输出:
<class 'str'>
Process finished with exit code 0