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

查看:26
本文介绍了是否可以在 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 上,使用 nonlocal 关键字:

On Python 3, use the nonlocal keyword:

nonlocal 语句使列出的标识符引用最近的封闭作用域中先前绑定的变量,不包括全局变量.这很重要,因为绑定的默认行为是首先搜索本地命名空间.该语句允许封装代码重新绑定全局(模块)范围之外的局部范围之外的变量.

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. 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.

def foo():
    a = 1
    def bar():
        nonlocal a
        a = 2
    bar()
    print(a)  # Output: 2

Python 2 上,使用可变对象(如列表或字典)并改变值而不是重新分配变量:

On Python 2, use a mutable object (like a list, or dict) and mutate the value instead of reassigning a variable:

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

foo()

输出:

[1, 1]

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

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