我有一个带有内部函数的函数。我想知道将变量传递给内部函数的正确方法是什么。据我所知,表格是默认传递的,尽管我不确定这是否是一个未记录的解决方法或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 (most recent call last):
File "test.py", line 16, in
function()
File "test.py", line 14, in function
inner_function()
File "test.py", line 5, in inner_function
tmp = c
UnboundLocalError: local variable 'c' referenced before assignment
将变量从“function”传递到“inner_function”的正确方法是什么?除了参数还有其他方法吗?为什么“c”变量引用有错误,而“a”表没有错误?
最佳答案
AFAIK c
抛出错误,因为在 inner_function
内部分配,因此它是与 中定义的
。变量 c
变量不同的变量函数a
和 b
之所以有效,是因为它们仅在 inner_function
处读取,因此不会被重新定义。将 c
和 d
重命名为 new_c
和 new_d
使其正常工作。
https://pyfiddle.io/fiddle/184e1778-adb7-4759-8951-da699751c31e/
有关 Python nested functions variable scoping 的更多信息
def function():
def inner_function():
if a[0] > b[0]:
print("a[0] = {0}, b[0] = {1}".format(a[0], b[0]))
tmp = c
new_c = d
new_d = tmp
a = [4, 3]
b = [2, 1]
c = 1
d = 2
inner_function()
function()
关于python - 将参数传递给内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49854272/