python 函数默认参数的问题

本文探讨了Python中使用列表作为函数默认参数时的一个常见陷阱。由于默认参数只在函数定义时评估一次,当修改一个可变默认参数(如列表)时,会影响到后续的函数调用。文章提供了避免这一陷阱的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值