Python, how can I change value of a variable in the parent scope?

空扰寡人 提交于 2019-12-05 04:10:59

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'

In python 3.0 and above you can use the nonlocal keyword.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!