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

☆樱花仙子☆ 提交于 2019-12-10 03:03:35

问题


for example: assginment statement will declare a new local variable.

foo = 'global'
def func1():
    foo = 'func1'
    def func2():
        foo = 'local variable in func2'

use global declaration will use the foo in global:

def func2():
    global foo
    foo = 'global changed in func2'  #changed the foo value in global scope

how can I change the variable foo in func1 scope?
Thanks for any help.

Edit:

Thank you Brandon Craig Rhodes, I finally understand your meaning.

if there are more than 3 scopes nested, I can store the variable in a list.

foo = ['global', 'function1', 'function2']
def func1():
    foo[1] = 'func1'
    def func2():
        foo[2] = 'func2'
        foo[1] = 'func1 modified in func2'

I just use a global variable actually.


so, if there are two functions nested, we can use

nonlocal foo 

and

global foo 

if there are more than three functions nested,
and each function use variables in other functions scope,
why don't we declare a global list variable?
Thank you for all your help!!!


回答1:


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'



回答2:


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



来源:https://stackoverflow.com/questions/5373377/python-how-can-i-change-value-of-a-variable-in-the-parent-scope

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