我认为在Python中没有任何方法可以做到这一点。定义闭包后,将捕获封闭范围内变量的当前状态,并且不再具有可直接引用的名称(从闭包外部)。如果要
foo()再次调用,则新的闭包将具有与封闭范围不同的变量集。
在简单的示例中,使用类可能会更好:
class foo: def __init__(self): self.var_a = 2 self.var_b = 3 def __call__(self, x): return self.var_a + self.var_b + xlocalClosure = foo()# Local closure is now "return 2 + 3 + x"a = localClosure(1) # 2 + 3 + 1 == 6# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0# ...but what magic? Is this even possible?localClosure.var_a = 0# Local closure is now "return 0 + 3 + x"b = localClosure(1) # 0 + 3 +1 == 4
如果您确实使用了这种技术,我将不再使用该名称,
localClosure因为它实际上不再是一个闭包。但是,它的工作原理与以前相同。



