为什么嵌套函数可以从外部函数访问变量,但不允许修改它们 [英] Why nested functions can access variables from outer functions, but are not allowed to modify them

查看:33
本文介绍了为什么嵌套函数可以从外部函数访问变量,但不允许修改它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的第二种情况下,Python 尝试查找局部变量.当它没有找到时,为什么它不能像第一种情况那样在外部范围内查找?

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?

这会在本地范围内寻找 x,然后在外范围内寻找:

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

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

这给出了在赋值之前引用的局部变量'x'错误:

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

我不允许修改函数 f2() 的签名,所以我不能传递和返回 x 的值.但是,我确实需要一种方法来修改 x.有没有办法明确告诉 Python 在外部作用域中查找变量名(类似于 global 关键字)?

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)?

Python 版本:2.7

Python version: 2.7

推荐答案

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

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

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

这篇关于为什么嵌套函数可以从外部函数访问变量,但不允许修改它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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