Python函数默认参数的一个小陷阱
来源:互联网 发布:湖北大学知行学院 编辑:程序博客网 时间:2024/05/22 11:31
def foo(a1, args = []): print "args before = %s" % (args) args.insert(0, 10) args.insert(0, 99999) print "args = %s " % (args)def main(): foo('a') foo('b')if __name__ == "__main__": main()
以上小程序会有如下输出:
args before = []args = [99999, 10] args before = [99999, 10]args = [99999, 10, 99999, 10]
按照通常的理解,第二次调用的args应该为默认值[],但为什么会变成上一次的结果呢?
查阅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, e.g.:
def whats_on_the_telly(penguin=None): if penguin is None: penguin = [] penguin.append("property of the zoo") return penguin
至此,原因已经很清楚了:函数中的参数默认值是一个可变的list, 函数体内修改了原来的默认值,而python会将修改后的值一直保留,并作为下次函数调用时的参数默认值
- Python函数默认参数的一个小陷阱
- Python函数默认参数的一个小陷阱
- [被坑纪念][转帖]Python函数默认参数的一个小陷阱
- Python 列表作为默认参数的陷阱
- Python默认参数的设计陷阱
- python中函数默认参数的陷阱(《改善python程序的91个建议》)
- 默认参数提升在可变参数函数的陷阱
- python 可变参数的一个陷阱
- Python函数参数默认值的陷阱
- Python函数的默认参数
- python 函数默认参数的问题
- 谈谈Python函数的默认参数
- Python函数参数默认值的陷阱和原理深究
- Python函数参数默认值的陷阱和原理深究
- Python函数参数默认值的陷阱和原理深究
- 【转载】Python函数参数默认值的陷阱和原理深究
- Java的一个小陷阱
- ListView的一个小陷阱!
- 字符设备驱动之Hello World
- C#流操作
- myeclipse+STRUTS+TOMCAT
- 打印所有匹配括号组合
- Mysql 内联结与外联结
- Python函数默认参数的一个小陷阱
- sqlite3数据库使用
- 前端学习-好的学习网站
- SCOPE 中 SPFILE、MEMORY、BOTH 的小小区别
- SQLITE3 使用总结
- Java_09_07课堂总结
- Linux 32和64位平台下支持LFS
- 获取当前坐标的方法
- Linux系统学习方法论(转)