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的更多相关文章

  1. scala - multiple overloaded alternatives of method bar define default arguments

    同名同位置默认参数不能overload def bar(i:Int,s:String="a"){} def bar(i:String,s:String="b") ...

  2. Python TypeError: not enough arguments for format string

    今天使用mysqldb执行query语句的时候,在执行这条语句的时候: select PROJ, DATE_FORMAT(MAX(DATE),'%Y-%m-%') AS MAXDATE, DATE_F ...

  3. 类模板成员函数默认值问题:an out-of-line definition of a member of a class template cannot have default arguments

    template <typename T> class A { ); }; template<typename T> ) { /* */ } 对于类似上文代码,VS编译器会报 ...

  4. Templates and Default Arguments

    Default parameters for templates in C++: Like function default arguments, templates can also have de ...

  5. Default arguments and virtual function

    Predict the output of following C++ program. 1 #include <iostream> 2 using namespace std; 3 4 ...

  6. [Python] Pitfalls: About Default Parameter Values in Functions

    Today an interesting bug (pitfall) is found when I was trying debug someone's code. There is a funct ...

  7. Python TypeError: not all arguments converted during string formatting ——元组tuple(a)和(a,)的区别

    今天写程序,想输出一个array的shape,原程序为: print('shape of testUImatrix:%s\nStart to make testUImatrix...'%(testui ...

  8. [LeetCode&Python] Problem 108. Convert Sorted Array to Binary Search Tree

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Fo ...

  9. [LeetCode&Python] Problem 427. Construct Quad Tree

    We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or ...

随机推荐

  1. Linux下安装Mysql(RPM安装)

    一.去官网下载本次安装须要的mysql版本号.我们须要安装的是5.1版本号的且centos系统是64位的.所下面载的是MySQL-community-5.1.73-1.rhel5.x86_64.rpm ...

  2. hdu 5318 The Goddess Of The Moon 矩阵高速幂

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=5318 The Goddess Of The Moon Time Limit: 6000/3000 MS ( ...

  3. 第十六周项目3:max带来的冲突

    问题及代码: /* *Copyright (c)2015,烟台大学计算机与控制工程学院 *All rights reserved. *文件名:project.cpp *作 者:陈文青 *完毕日期:20 ...

  4. Unity Image Effect

    1.工作原理 Image Effect是运用于一个Camera,将Camera视见体最终看到的二维图像内容作为一个2DTexture传递给一个Shader, 然后在Shader的Fragment渲染阶 ...

  5. ConfigurationSection

    https://msdn.microsoft.com/en-us/library/system.configuration.configurationsection(v=vs.110).aspx Re ...

  6. POJ 3671 DP or 乱搞

    思路: 1.DP f[i][j]:前i个数 最后一个数是j的最小花费 f[i][j]=min(f[i][j],f[i-1][k]+(a[i]!=j));1<=k<=j 这种做法比较有普遍性 ...

  7. Java类和对象9

    (1)创建一个叫做机动车的类:属性:车牌号(String),车速(int),载重量(double)功能:加速(车速自增).减速(车速自减).修改车牌号,查询车的载重量.编写两个构造方法:一个没有形参, ...

  8. Swift学习笔记(5):集合类型

    目录: 数组:Array 集合:Set 字典:Dictionary Swift提供Array(有序集合数据).Set(无序无重复集合)和Dictionary(无序键值对集合)三种基本集合类型来存储明确 ...

  9. 集合HashSet的使用

    集合中的HashSet底层是通过Hash表实现,HashSet的特点是元素唯一,但用到Hash表就跟hashCode()有了密不可分的联系,所以HashSet的唯一性是通过hashCode()方法来保 ...

  10. Tiles入门及项目实战

    1.Apache Tiles™ Apache Tiles是一个模板布局框架.最初是为了简化Web应用界面开发,如今已不限于JavaEE Web环境. Tiles允许开发人员定义页面片段,它们在运行时会 ...