从Python中的双嵌套函数中访问变量

kzh*_*kzh 5 python global-variables nested-function

以下代码:

x = 0
print "Initialization: ", x
def f1():
    x = 1
    print "In f1 before f2:", x
    def f2():
        global x
        x = 2
        print "In f2:          ", x
    f2()
    print "In f1 after f2: ", x
f1()
print "Final:          ", x
Run Code Online (Sandbox Code Playgroud)

打印:

Initialization:  0
In f1 before f2: 1
In f2:           2
In f1 after f2:  1
Final:           2
Run Code Online (Sandbox Code Playgroud)

有没有办法f2访问f1变量?

int*_*jay 6

在Python 3中,您可以在f2中将x定义为非本地.

在Python 2中,您不能直接分配给f2中的f1的x.但是,您可以读取其值并访问其成员.所以这可能是一个解决方法:

def f1():
    x = [1]
    def f2():
        x[0] = 2
    f2()
    print x[0]
f1()
Run Code Online (Sandbox Code Playgroud)


nik*_*kow 6

你可以访问变量,问题是赋值.在Python 2中,无法重新绑定x到新值.有关详细信息,请参阅PEP 227(嵌套范围).

在Python 3中,您可以使用new nonlocal关键字而不是global.见PEP 3104.