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

2024-06-28 18:49:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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中的另一个值?你知道吗


Tags: 代码testtrue定义defpassahaprint
1条回答
网友
1楼 · 发布于 2024-06-28 18:49:14

在Python3中,可以将变量设置为非局部变量

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

    while True:
        printA()

test()

相关问题 更多 >