[Python] Problem with Default Arguments

本文通过一个例子解释了在Python中使用可变类型作为函数默认参数时可能遇到的问题。当默认参数被修改时,后续调用该函数的行为将受到影响,导致不符合预期的结果。

Default arguments are a helpful feature, but there is one situation where they can be surprisingly unhelpful. Using a mutable type (like a list or dictionary) as a default argument and then modifying that argument can lead to strange results. It's usually best to avoid using mutable default arguments: to see why, try the following code locally.

 

Consider this function which adds items to a todo list. Users can provide their own todo list, or add items to a default list:

def todo_list(new_task, base_list=['wake up']):
    base_list.append(new_task)
    return base_list

 

We can call the function like this:

>>> todo_list("check the mail")
['wake up', 'check the mail']

 

So if later on we call it again:

>>> todo_list("begin orbital transfer")

 

The result is actully:

['wake up', 'check the mail', 'begin orbital transfer']

The list object base_list is only created once: when the todo_list function is defined. Lists are mutable objects. This list object is used every time the function is called, it isn't redefined each time the function is called. Because todo_list appends an item to the list, base_list can get longer each time that todo_list is called.

转载于:https://www.cnblogs.com/Answer1215/p/7906368.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值