且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python,如何在父范围内更改变量的值?

更新时间:2021-12-01 06:22:29

我相信在Python 3中,您可以使用nonlocal关键字来获得在非全局范围内修改变量的权限.在Python 2中,您不能在封闭范围内重新分配foo.而是将foo设置为等于诸如列表[]的可变对象,然后将要存储的值粘贴在列表中:

In Python 3, I believe, you can use the nonlocal keyword to get permission to modify a variable in an enclosing non-global scope. In Python 2, you cannot reassign foo in an enclosing scope; instead, set foo equal to a mutable object like a list [] and then stick the value you want stored in the list:

def func1():
    foo = [None]
    def func2():
        foo[0] = 'Test'