def add(i, l = []):
l.append(i)
print(l)
>> add(1)
[1]
>> add(2)
[1, 2]
>> add(3)
[1, 2, 3]
按说默认参数是个空列表,但实际可以发现,参数 l 调用的是上一次的结果,贴一下 Python manual 上的说法:
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 that 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 的默认参数实际是一个指向 PyObject 的指针,对于 list 或者 dict 之类的值,即使 list 的内容变化了,指针还是没变的,如果默认参数是个数字或者常量,变化之后,应该会生成一个新的 PyObject 。