问题描述
有没有办法修改闭包中的一个变量的绑定值?
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
$ b localClosure = foo()
#本地闭包现在是return 2 + 3 + x
a = localClosure(1)#2 + 3 + 1 == 6
#DO某些魔法在这里把var_a的闭包变成0
#...但是什么魔术?这是可能吗?
#本地闭包现在是return 0 + 3 + x
b = localClosure(1)#0 + 3 +1 == 4
解决方案我认为在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 + x
localClosure = foo()
#本地闭包现在是return 2 + 3 + x
a = localClosure(1)#2 + 3 + 1 == 6
#让一些魔法把闭包的var_a变成0
#...但是什么魔术?这是可能吗?
localClosure.var_a = 0
#本地闭包现在为return 0 + 3 + x
b = localClosure(1)#0 + 3 +1 == 4
如果你使用这种技术,我将不再使用
localClosure
,因为它不再是一个闭包。但是,它的工作原理与一样。Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
def foo(): var_a = 2 var_b = 3 def _closure(x): return var_a + var_b + x return _closure localClosure = 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? # Local closure is now "return 0 + 3 + x" b = localClosure(1) # 0 + 3 +1 == 4
解决方案I don't think there is any way to do that in Python. When the closure is defined, the current state of variables in the enclosing scope is captured and no longer has a directly referenceable name (from outside the closure). If you were to call
foo()
again, the new closure would have a different set of variables from the enclosing scope.In your simple example, you might be better off using a class:
class foo: def __init__(self): self.var_a = 2 self.var_b = 3 def __call__(self, x): return self.var_a + self.var_b + x localClosure = 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
If you do use this technique I would no longer use the name
localClosure
because it is no longer actually a closure. However, it works the same as one.这篇关于在Python中修改闭包的绑定变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!