python - 将参数传递给内部函数

标签 python parameter-passing

我有一个带有内部函数的函数。我想知道将变量传递给内部函数的正确方法是什么。据我所知,表格是默认传递的,尽管我不确定这是否是一个未记录的解决方法或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 变量不同的变量函数。变量 ab 之所以有效,是因为它们仅在 inner_function 处读取,因此不会被重新定义。将 cd 重命名为 new_cnew_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/

相关文章:

python - Matplotlib 动画无法正确保存

python - 删除 numpy 数组的重复行

python - 客户端使用 python 套接字接收两条单独的消息

c++ - 为什么会出现这种性能下降?

javafx - 传递参数JavaFX FXML

python - urllib3 HTTPResponse.read() 返回空字节

python - Numpy - 创建重叠的 3D 子数组作为内存效率高的向量

asp.net-mvc - 如何使用 Get 参数在 ASP.NET MVC 中传递复杂对象?

javascript - 使用参数从 PHP 调用带有参数(在特定文件中)的 Javascript 函数

javascript - 将传递的函数参数与默认参数合并