【发布时间】:2011-12-09 15:45:07
【问题描述】:
给定以下代码:
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() 阅读它,但是如何修改它呢?
【问题讨论】:
-
只要
b是可变的就可以。对b的赋值将掩盖外部范围。 -
nonlocal没有被向后移植到 2.x 是 Python 的尴尬之一。这是闭包支持的内在组成部分。 -
看起来使用非本地或使用列表,如上所述,不适用于类。 Python 错误地假设变量将在作用域类中,而不是在函数类之一的内部。
标签: python python-2.7