2

在我的程序中经历了这种奇怪。这是造成麻烦的部分的片段:

#!/usr/bin python
def test_func( newList, myList=[] ):
    for t in newList:
        for f in t:
            myList.append(f)
    return myList

print test_func([[3, 4, 5], [6, 7, 8]])
print test_func([[9, 10, 11], [12, 13, 14]])

第一次调用该函数时,它会产生

[3, 4, 5, 6, 7, 8]

第二次

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

我不知道它为什么这样做。python 函数是静态的,因为它们保留了在后续调用中传递给它们的值,还是我的代码中缺少某些内容?

4

3 回答 3

6

不要使用 mutable 作为关键字参数。

def test_func( newList, myList=None ):
    myList = [] if myList is None else myList     
于 2013-08-09T07:09:37.443 回答
5

Although an answer has been accepted, it is interesting as well as important to understand why this happens, so as to avoid not-so-obvious pitfalls.

An excerpt from the Python documentation for compound statements :

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function

Please refer to the StackOverflow Discussion here for a discussion related to mutable arguments within the Python language. The discussion points to a very interesting and informative article on Effbot - Python Default Values which gives a good explanation of why this behavior is observed and the places where such a behavior is desirable - for e.g. a calculator function that performs very computing-intensive calculations may use a dictionary mutable as a default parameter to store the results of a calculation keyed by the parameters used for the calculation. In such a case, when the client requests for a calculation to be performed, the function can look up the dictionary mutable and return the values if already present, else perform the calculation.

Hopefully, this answer provides an insight into this "astonising" behavior of python and help in designing functions that work correctly and are performant.

于 2013-08-09T16:29:35.307 回答
2

Python 存储可选参数的默认值。如果你修改了它们的值,它仍然会在后续的调用中被修改。

这个线程有一个很好的解释: Python optional parameters

要解决您的情况,请在未指定 myList 时每次调用该函数时创建一个新的 myList 实例。

像这样:

#!/usr/bin python
def test_func( newList, myList=None ):
    if myList is None:
        myList = []
    for t in newList:
        print "t:", t
        for f in t:
            myList.append(f)
    return myList

print test_func([[3, 4, 5], [6, 7, 8]])
print test_func([[9, 10, 11], [12, 13, 14]])
于 2013-08-09T07:29:07.047 回答