为什么嵌套函数可以从外部函数访问变量,但是不允许修改它们[duplicate]

时间:2022-08-11 20:58:15

This question already has an answer here:

这个问题已经有了答案:

In the 2nd case below, Python tries to look for a local variable. When it doesn't find one, why can't it look in the outer scope like it does for the 1st case?

在下面的第二种情况中,Python尝试查找一个本地变量。当它找不到一个的时候,为什么不能像第一个那样从外部观察呢?

This looks for x in the local scope, then outer scope:

这是在局部范围内寻找x,然后是外部作用域:

def f1():
    x = 5
    def f2():
         print x

This gives local variable 'x' referenced before assignment error:

这使局部变量'x'在分配错误之前被引用:

def f1():
    x = 5
    def f2():
        x+=1

I am not allowed to modify the signature of function f2() so I can not pass and return values of x. However, I do need a way to modify x. Is there a way to explicitly tell Python to look for a variable name in the outer scope (something similar to the global keyword)?

我不允许修改函数的签名f2()所以我不能传递和返回值x的。不过,我确实需要一种方法来修改x。有办法明确告诉Python寻找外层作用域的变量名(类似于全局关键字)?

Python version: 2.7

Python版本:2.7

2 个解决方案

#1


46  

def f1():
    x = { 'value': 5 }
    def f2():
        x['value'] += 1

Workaround is to use a mutable object and update members of that object. Name binding is tricky in Python, sometimes.

解决方法是使用可变对象并更新该对象的成员。在Python中,有时候名称绑定很棘手。

#2


45  

In Python 3.x this is possible:

Python 3。x这是可能的:

def f1():
        x = 5
        def f2():
                nonlocal x
                x+=1
        return f2

The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.

对于Python 2来说,问题和解决方案。x也在这篇文章中给出。此外,请阅读PEP 3104了解更多有关此主题的信息。

#1


46  

def f1():
    x = { 'value': 5 }
    def f2():
        x['value'] += 1

Workaround is to use a mutable object and update members of that object. Name binding is tricky in Python, sometimes.

解决方法是使用可变对象并更新该对象的成员。在Python中,有时候名称绑定很棘手。

#2


45  

In Python 3.x this is possible:

Python 3。x这是可能的:

def f1():
        x = 5
        def f2():
                nonlocal x
                x+=1
        return f2

The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.

对于Python 2来说,问题和解决方案。x也在这篇文章中给出。此外,请阅读PEP 3104了解更多有关此主题的信息。