如何在Python中使用以前作用域中的变量

时间:2016-04-25 01:12:04

标签: python scope

我有以下代码:

def test():
    def printA():
        def somethingElse():
            pass
        print(a)
        aHA = a[2]


    a = [1, 2, 3]
    while True:
        printA()

test()

我注意到此代码可以正常使用,但如果我将aHA更改为a,则表示a未定义。

有没有办法将a设置为printA中的另一个值?

1 个答案:

答案 0 :(得分:3)

在python 3中,您可以将变量设置为非本地

def test():
    a = [1, 2, 3]
    def printA():
        nonlocal a
        def somethingElse():
            pass
        print(a)
        a = a[2]

    while True:
        printA()

test()