Passing argument from Parent function to nested function Python(将参数从父函数传递给嵌套函数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)
这篇关于将参数从父函数传递给嵌套函数Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将参数从父函数传递给嵌套函数Python
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
