码迷,mamicode.com
首页 > 编程语言 > 详细

[Python] Problem with Default Arguments

时间:2017-11-27 23:37:25      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:void   hat   can   default   task   because   ted   div   led   

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.

[Python] Problem with Default Arguments

标签:void   hat   can   default   task   because   ted   div   led   

原文地址:http://www.cnblogs.com/Answer1215/p/7906368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!