【发布时间】:2013-08-22 02:34:46
【问题描述】:
这可能更适合讨论组,但我不精通 语言的内部(甚至语言本身)。无论如何,困扰我的是:
如果 python 允许使用 nonlocal 关键字对外部作用域进行干扰(副作用),那么为什么它不允许通过以下方式对函数参数进行类似的干扰
允许通过引用传递参数:
现在可以:
>>> def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
>>> outer()
inner: 2
outer: 2
为什么不 - 或者如果我们有什么可能会出错:
>>> def outer():
x = 1
def inner(byref x):
x = 2
print("inner:", x)
inner(x)
print("outer:", x)
>>> outer()
inner: 2
outer: 2
(使用一些关键字,如 'byref' 或 'nonlocal,仅用于说明)。
【问题讨论】:
标签: python pass-by-reference python-nonlocal