python中nonlocal关键字
''' nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。 ''' def work(): x = 0 def new_work(): nonlocal x x += 3 return x return new_work f=work() print(f()) print(f()) print(f())
# 运行结果: 3 6 9
''' 使用global 实现 ''' a =0 def new_work(): global a a=a+3 return a print(new_work()) print(new_work()) print(new_work())
# 运行结果: 3 6 9
def dosometing(): a =25 def add(x): d=a+x return d return add a = 10 f=dosometing() print(f(5)) print(f(5)) print(f(5))
# 运行结果 30 30 30
''' 闭包= 函数+环境变量 nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。 ''' def dosometing(): a =25 def add(x): nonlocal a a=a+x return a return add a = 10 f=dosometing() print(f(5)) print(f(5)) print(f(5))
# 运行结果: 30 35 40