oct*_*ref 2 python arguments nested-loops nested-function
这是我的代码:
def f(x):
def g(n):
if n < 10:
x = x + 1
g(n + 1)
g(0)
Run Code Online (Sandbox Code Playgroud)
当我评估f(0)时,会出现错误"在赋值之前引用x".
但是,当我使用"print x"而不是"x = x + 1"时,它会起作用.
似乎在g的范围内,我只能使用x作为"使用事件"而不是"绑定事件".我想问题是f只传递给g的值为g.
我是否理解正确?如果没有,有人可以解释为什么在引用前没有定义"x = x + 1"的左侧?
谢谢
你正确理解它.您不能x
在Python 2中使用嵌套作用域进行分配.
在Python 3中,您仍然可以通过将变量标记为nonlocal
; 来将其用作绑定事件.这是仅为此用例引入的关键字:
def f(x):
def g(n):
nonlocal x
if n < 10:
x = x + 1
g(n + 1)
g(0)
Run Code Online (Sandbox Code Playgroud)
在python 2中,你有一些解决方法; 使用mutable来避免需要绑定它,或者(ab)使用函数属性:
def f(x):
x = [x] # lists are mutable
def g(n):
if n < 10:
x[0] = x[0] + 1 # not assigning, but mutating (x.__setitem__(0, newvalue))
g(n + 1)
g(0)
Run Code Online (Sandbox Code Playgroud)
要么
def f(x):
def g(n):
if n < 10:
g.x = g.x + 1
g(n + 1)
g.x = x # attribute on the function!
g(0)
Run Code Online (Sandbox Code Playgroud)