您可以分配给父函数中定义的变量吗? [英] Can you assign to a variable defined in a parent function?

查看:53
本文介绍了您可以分配给父函数中定义的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Python 嵌套函数变量作用域

经过多次反复试验,我最终发现这行不通:

After much trial and error I have eventually discovered that this doesn't work:

def a():
    def b():
        print x
        x=2
    x = 1
    b()
    print x

您得到一个异常(x 在被引用之前未定义).所以看起来 b 可以从 x 读取,但是如果它试图赋值给它,Python 会将它对 'x' 的解释更改为一个局部变量,现在没有定义.

You get an exception (x not defined before being referenced). So it looks like b can read from x, but if it tries to assign to it, Python changes its interpretation of 'x' to be a local variable, which is now not defined.

问我自己病态的好奇心:有没有办法实现这一点?有没有办法显式访问父函数的范围?(x 不是全局的)

Question for my own sick curiosity: is there any way of achieving this? Is there a way of explicitly accessing the scope of the parent function? (x is not global)

推荐答案

nonlocal 语句 可以做到这一点.

The nonlocal statement in Python 3 will do this.

编辑:在 Python 2 中,没有一种简单的方法可以做到.如果您需要此功能,我建议您使用一些可变容器对象.例如:

Edit: In Python 2, there's not a simple way to do it. I suggest you use some mutable container object if you need this capability. For example:

def a():
    def b():
        print d["x"]
        d["x"]=2
    d = dict(x=1)
    b()
    print d["x"]

如果您绝对必须为 CPython 2 模拟 nonlocal,您可以通过 Python C API 以这种方式破解它:

If you absolutely must emulate nonlocal for CPython 2, you can hack it with the Python C API this way:

import ctypes
import inspect

locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast
locals_to_fast.restype = None
locals_to_fast.argtypes = [ctypes.py_object, ctypes.c_int]

def set_in_frame(frame, name, value):
    frame.f_locals[name] = value
    locals_to_fast(frame, 1)

def a():
    def b(frame=inspect.currentframe()):
        print x
        set_in_frame(frame, "x", 2)
    x = 1
    b()
    print x

您也可以将框架设置为本地,而不是调用 PyFrame_LocalsToFast(),您可以操作 a 的字节码,使其使用 LOAD_NAME 而不是 LOAD_FAST.请不要做这些事情.对于您的用例,肯定有更好的解决方案.

You could also set the frame local, and instead of calling PyFrame_LocalsToFast(), you could manipulate the bytecode of a so that it uses LOAD_NAME instead of LOAD_FAST. Please don't do either of these things. There is surely a better solution for your use case.

这篇关于您可以分配给父函数中定义的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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