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