python中label怎么绑定变量_在Python中修改闭包的绑定变量

这篇博客探讨了在Python中是否可以修改闭包内部变量的值。作者指出,一旦闭包创建,其对封闭作用域变量的引用就被固定,无法直接修改。为实现类似效果,建议使用类来替代闭包,并展示了如何通过实例变量改变行为。
摘要由CSDN通过智能技术生成

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值