Python,如何在父范围内更改变量的值? [英] Python, how can I change value of a variable in the parent scope?

查看:107
本文介绍了Python,如何在父范围内更改变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如: assginment语句将声明一个新的局部变量.

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声明将在global中使用foo:

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

如何在func1范围内更改变量foo?
感谢您的帮助.

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

谢谢布兰登·克雷格·罗兹,我终于明白了你的意思.

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 

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!!!

推荐答案

我相信在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'

这篇关于Python,如何在父范围内更改变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆