简体   繁体   English

将列表作为python函数的参数传递的问题

[英]Issue with passing list as argument to python function

def foo(val, arr=[]):
    arr.append(val)
    return arr

print(foo(1)) ---> outputs [1]
print(foo(2)) ---> outputs [1, 2]

Above happens because the default value (an empty list) was evaluated once, when the function was compiled, then re-used on every call to the function. 发生上述情况是因为在编译函数时对默认值(一个空列表)进行了一次评估,然后在每次调用该函数时将其重新使用。 If this is the case then I am not able to understand output of below python code 如果是这种情况,那么我将无法理解以下python代码的输出

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l) 

f(2)
f(3,[3,2,1])
f(3)
#This outputs below
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

Here in second call f(), list has been changed to [3, 2, 1, 0, 1, 4] but in the third call to f() uses list created in first call f() ie [0, 1] 这里在第二次调用f()中,列表已更改为[3, 2, 1, 0, 1, 4]但在第三次调用f()中使用了在第一次调用f()中创建的列表,即[0, 1]

I am unable to understand how third call is not using list crated during 2nd f() call. 我无法理解在第二次f()调用期间第三次调用是如何不使用列表创建的。

First gotcha in the list http://docs.python-guide.org/en/latest/writing/gotchas/ 列表http://docs.python-guide.org/en/latest/writing/gotchas/中的第一个陷阱

The list is only created once, so if you modify it then that modified version is used next time. 该列表仅创建一次,因此,如果您对其进行修改,则下次使用该修改的版本。

In the second call f(3, [3,2,1]) ; 在第二个调用f(3, [3,2,1]) ; it isn't using the default list, it's using the one supplied by you. 它不是使用默认列表,而是使用您提供的列表。 So when you call a third time you're using the default list which was only modified by the first call. 因此,当您第三次通话时,您使用的是默认列表,该列表仅在第一次通话时进行了修改。

as an example, looking up the memory addess for each object using id : 例如,使用id查找每个对象的内存地址:

def foo(a=[]):
    print id(a)

foo()   #140378224732136
foo([]) #140378224687944
foo()   #140378224732136

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM