Python静态函数?

2024-04-25 17:57:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的节目中经历了这种奇怪的事。下面是一段引起麻烦的部分:

#!/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]])

第一次调用函数时,它将生成

^{pr2}$

第二次

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

我不知道为什么会这样。python函数是静态的,因为它们保留了在后续调用中传递给它们的值,还是我在代码中遗漏了什么?在


Tags: intestforreturnbinusrdef节目
3条回答

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

def test_func( newList, myList=None ):
    myList = [] if myList is None else myList     

虽然一个答案已经被接受了,但理解为什么会发生这种情况是有趣的,也是重要的,这样可以避免不那么明显的陷阱。在

摘自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

有关Python语言中可变参数的讨论,请参考StackOverflow Discussion here。讨论指向了一篇关于Effbot - Python Default Values的非常有趣且信息丰富的文章,该文章很好地解释了为什么会观察到这种行为,以及这种行为在哪些地方是可取的——例如,执行计算密集型计算的计算器函数可以使用字典可变项作为默认参数来存储结果由用于计算的参数键控的计算。在这种情况下,当客户机请求执行计算时,函数可以查找可变字典并返回已存在的值,否则执行计算。在

希望这个答案能让我们深入了解python的这种“惊人”行为,并有助于设计正确工作且性能良好的函数。在

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

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

为了解决这个问题,在指定myList not时,每次调用函数时都要创建一个新的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]])

相关问题 更多 >