- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在编写的有关变量范围的内部函数时遇到了问题。我已经设法简化代码以指出确切的问题。所以开始:
def outer(foo):
def inner(bar):
print(foo)
print(bar)
return inner
if __name__ == "__main__":
function = outer("foo")
function("bar")
我将得到预期的输出:
foo
bar
但是,如果我尝试重新分配 foo,则会出现错误:
def outer(foo):
def inner(bar):
foo = "edited " + foo
print(foo)
print(bar)
return inner
给出:
UnboundLocalError: local variable 'foo' referenced before assignment
这让我想起了全局变量,您可以在其中正常“读取”它们,但要“写入”您必须执行“global variable; variable=...”。是一样的情况吗?如果是这样,是否有一个关键字允许从内部修改 foo?还有为什么?当然,一旦我创建了函数,那么 foo 就固定用于该函数。 IE。不是全局性的。这里避免了什么问题?
最佳答案
[...] is there a keyword that allows modification of foo from within inner?
确实有这样一个关键字:nonlocal
def outer(foo):
def inner(bar):
nonlocal foo
foo = "edited " + foo
print(foo)
print(bar)
return inner
outer("foo")("bar")
输出:
edited foo
bar
来自docs :
nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
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.
Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.
至于为什么
部分:
代码块中的任何赋值 (x = y) 都会将变量的范围更改为当前范围。因此,要引用和修改 (*) 来自全局范围的变量,我们需要关键字 global
,但在这种情况下,我们需要来自“最近的封闭”范围的变量,因此我们需要关键字 非本地
。
(*) 通过赋值修改;可变全局变量仍然可以使用它们各自的方法修改,而无需全局/非局部关键字。
关于Python 内部函数变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57007407/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!