将参数从父函数传递给嵌套函数Python
问题描述
这是我的代码:
def f(x):
def g(n):
if n < 10:
x = x + 1
g(n + 1)
g(0)
当我评估 f(0) 时,会出现错误x referenced before assignment".
When I evaluate f(0), there would be an error "x referenced before assignment".
但是,当我使用 "print x" 而不是 "x = x + 1" 时,它会起作用.
However, when I use "print x" instead of "x = x + 1" , it will work.
似乎在g的范围内,我只能将x用作使用事件"而不是绑定事件".我猜问题是 f 只传递给 g 的值 x.
It seems that in the scope of g, I can only use x as an "use occurrence" but not a "binding occurrence". I guess the problem is that f passes to g only the VALUE of x.
我是否理解正确?如果不是,有人可以解释为什么x = x + 1"的左侧在引用之前没有定义吗?
Am I understanding it correctly or not? If not, can someone explain why the left side of "x = x + 1" is not defined before reference?
谢谢
解决方案
你理解正确.您不能使用 x
在 Python 2 的嵌套范围内赋值.
You are understanding it correctly. You cannot use x
to assign to in a nested scope in Python 2.
在 Python 3 中,您仍然可以通过将变量标记为 nonlocal
来将其用作绑定实例;这是为此用例引入的关键字:
In Python 3, you can still use it as a binding occurrence by marking the variable as nonlocal
; this is a keyword introduced for just this usecase:
def f(x):
def g(n):
nonlocal x
if n < 10:
x = x + 1
g(n + 1)
g(0)
在 python 2 中,您有一些变通方法;使用可变的以避免需要绑定它,或(ab)使用函数属性:
In python 2, you have a few work-arounds; using a mutable to avoid needing to bind it, or (ab)using a function property:
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)
或
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)
相关文章