python不可“用可变对象作默认参数”
来源:互联网 发布:project是什么软件 编辑:程序博客网 时间:2024/06/06 06:35
默认参数很有用,但使用不当,也会掉坑里。默认参数有个最大的坑,演示如下:
先定义一个函数,传入一个list,添加一个END
再返回:
def add_end(L=[]): L.append('END') return L
当你正常调用时,结果似乎不错:
>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']
当你使用默认参数调用时,一开始结果也是对的:
>>> add_end()['END']
但是,再次调用add_end()
时,结果就不对了:
>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']
很多初学者很疑惑,默认参数是[]
,但是函数似乎每次都“记住了”上次添加了'END'
后的list。
原因解释如下:
Python函数在定义的时候,默认参数L
的值就被计算出来了,即[]
,因为默认参数L
也是一个变量,它指向对象[]
,每次调用该函数,如果改变了L
的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]
了。
https://docs.python.org/2/reference/compound_stmts.html#function-definitions
"Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluatedonce, when the function is defined, and that the 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.(as shown above)
参考:https://m.aliyun.com/yunqi/wenji/126981
- python不可“用可变对象作默认参数”
- python--可变对象作为默认参数
- python参数传递问题与可变/不可变对象
- python的默认参数和可变对象研究
- python函数--默认参数指向不可变对象
- python 可变对象与不可变对象
- python可变对象和不可变对象
- python可变对象与不可变对象
- (python)可变对象/不可变对象
- Python-可变对象和不可变对象
- python中 可变与不可变对象
- python的可变和不可变对象
- Python 中可变与不可变对象
- python函数参数是值传递还是引用传递:取决于对象内容可变不可变
- Python基础:Python可变对象和不可变对象
- Python基础:Python可变对象和不可变对象
- Python 函数默认参数不能使用可变对象,如List,dict
- 关于Python参数传递时,传递可变对象(mutable)和不可变更对象(immutable)的误区
- 防止表单重复提交
- ZooKeeper 安装Windows环境
- 多进程与多线程
- 基于zipkin和brave完成对dubbo的链路追踪
- linux iscsi initiator 安装配置
- python不可“用可变对象作默认参数”
- android java项目到kotlin的转换
- 短信相关的AT指令以及信令
- 1014. 福尔摩斯的约会 (20)
- VTK读取图片,QT中显示
- NIO简介
- QTabWidget 竖向 QTabBar横向
- jQuery对象和DOM对象的相互转换
- 用CSS模拟单选框