Python is Best

Python——nonlocal语句

2017-09-25  本文已影响8人  So_ProbuING

nonlocal介绍

格式

def func():
      nonloacal name1,name2,....
>>> def tester(start):
...     state = start
...     def nested(label):
...             state+=1
...             print(label,state)
...     return nested
... 
>>> F = tester('hello')
>>> F('cdef')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in nested
UnboundLocalError: local variable 'state' referenced before assignment
>>> 

使用nonlocal进行修改
将嵌套的nested中的state声明一个nonlocal,我们就可以在nested函数中修改了

>>> def tester(start):
...     state = start
...     def nested(state):
...             state+=1
...             print(state)
...     return nested
... 
>>> F = tester(25)
>>> F(22)
23

边界情况

上一篇 下一篇

猜你喜欢

热点阅读