在 Python 中修改闭包的绑定变量 [英] Modify bound variables of a closure in Python

查看:23
本文介绍了在 Python 中修改闭包的绑定变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以修改闭包内变量之一的绑定值吗?查看示例以更好地理解它.

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

推荐答案

我认为在 Python 中没有任何方法可以做到这一点.当闭包被定义时,封闭作用域中变量的当前状态被捕获并且不再具有直接可引用的名称(来自闭包外部).如果您再次调用 foo(),新的闭包将具有与封闭作用域不同的一组变量.

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

如果你确实使用了这种技术,我将不再使用名称 localClosure,因为它实际上不再是一个闭包.但是,它的工作原理与 1 相同.

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 中修改闭包的绑定变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆