Python状态保持
全局 global
1 def tester(start):
2 global state
3 state = start
4 def nested(label):
5 global state
6 print(label,state)
7 state += 1
8 return nested # 都声明为全局,只会保存一个副本,会覆盖
非本地 nonlocal
1 def tester(start):
2 state = start
3 def nested(label):
4 nonlocal state
5 print(label,state)
6 state += 1
7 return nested # Python3 主流 但是作用域只能是嵌套作用域
类 class
1 class nested():
2 def __init__(self,state):
3 self.state = state
4 def __call__(self,label):
5 print(self.state,label)
6 self.state += 1 # 有点老了
函数属性 函数名.变量名
1 def tester(start):
2 def nested(label):
3 print(label,nested.state)
4 nested.state += 1
5 nested.state = start
6 return nested # 未曾用过的黑魔法,这回就知道了