是否可以修改python中位于外部但不是全局范围内的变量? [英] Is it possible to modify variable in python that is in outer, but not global, scope?

查看:78
本文介绍了是否可以修改python中位于外部但不是全局范围内的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

def A() :
    b = 1

    def B() :
        # I can access 'b' from here.
        print( b )
        # But can i modify 'b' here? 'global' and assignment will not work.

    B()
A()

对于B()中的代码,函数变量b在外层作用域,不在全局作用域.是否可以从 B() 函数中修改 b 变量?我当然可以从这里和 print() 读取它,但是如何修改它?

For the code in B() function variable b is in outer scope, but not in global scope. Is it possible to modify b variable from within B() function? Surely I can read it from here and print(), but how to modify it?

推荐答案

Python 3.x 具有 nonlocal 关键字.我认为这可以满足您的需求,但我不确定您是在运行 python 2 还是 3.

Python 3.x has the nonlocal keyword. I think this does what you want, but I'm not sure if you are running python 2 or 3.

非本地语句导致列出的标识符引用先前在最近的封闭范围内绑定变量.这是重要,因为绑定的默认行为是搜索首先是本地命名空间.该语句允许封装的代码除了全局范围之外,重新绑定局部范围之外的变量(模块)范围.

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

对于 python 2,我通常只使用可变对象(如列表或字典),并改变值而不是重新分配.

For python 2, I usually just use a mutable object (like a list, or dict), and mutate the value instead of reassign.

示例:

def foo():
    a = []
    def bar():
        a.append(1)
    bar()
    bar()
    print a

foo()

输出:

[1, 1]

这篇关于是否可以修改python中位于外部但不是全局范围内的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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