【发布时间】:2018-09-26 00:19:55
【问题描述】:
我有一个具有内部功能的功能。我想知道将变量传递给内部函数的正确方法是什么。从我所见,默认情况下会传递表格,尽管我不确定这是未记录的解决方法还是 python 设计。
def function():
def inner_function():
if a[0] > b[0]:
print("a[0] = {0}, b[0] = {1}".format(a[0], b[0]))
tmp = c
c = d
d = tmp
a = [4, 3]
b = [2, 1]
c = 1
d = 2
inner_function()
function()
python test.py 输出:
$ python test.py a[0] = 4, b[0] = 2 Traceback(最近一次调用最后一次):
文件“test.py”,第 16 行,在
函数()
File "test.py", line 14, in functioninner_function()
File "test.py", line 5, in inner_functiontmp = c
UnboundLocalError: 赋值前引用了局部变量 'c'
将变量从“function”传递到“inner_function”的正确方法是什么?除了参数还有其他方法吗?为什么“c”变量引用而不是“a”表有错误?
【问题讨论】:
-
为什么不直接将变量作为参数发送给内部函数,然后再返回呢?
-
您使用的是哪个 python 版本?这在这里很重要,因为 python3 针对这种情况有一个特定的关键字:smallsurething.com/a-quick-guide-to-nonlocal-in-python-3