Python中默认参数值

本文探讨了Python中默认参数使用不当可能导致的问题,特别是当默认参数是可变对象时,每次函数调用都会修改这个对象,导致意外的结果。文章通过具体示例展示了如何避免这一陷阱。

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

关于Python默认参数,假如默认参数是可变(mutable)对象是会有副作用的,一个函数参数的默认值,仅仅在该函数定义的时候,被赋值一次如此,只有当函数第一次被定义的时候,才将参数的默认值初始化到它的默认值(如一个空的列表)

如:

>>> def function(data=[]):
	data.append(1)
	return data

>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]

当def function(data=[])执行完成,预先计算的值,即data就会被每次函数调用所使用,尤其是当默认参数是可变的对象时,参数可以"类比为全局变量,当然这个全局变量的范围是在函数范围内的"

引用其他博文所说:“

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
def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin
def f(x, I=[]):  # 函数初始化定义,I仅仅被赋值一次
    print('程序运行前I的值为: {}'.format(I))
    for i in range(x):
        I.append(i*i)
    print('I id is : {} '.format(id(I)))
f(2) # 函数被调用,会从初始化义读取I值,并且更改I值f(2,[3,2,1]) # 函数重新调用,I参数被赋值f(3) # 函数重新调用,虽然在函数体内I被重新赋值为空[],但是调用I的值是在初始化的定义的值程序运行前I的值为: []
I id is : 42474792 
程序运行前I的值为: [3, 2, 1]
I id is : 42474872 
程序运行前I的值为: [0, 1]
I id is : 42474792 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值