[Python] Problem with Default Arguments
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.
相关文章
- pycharm关闭自动补全_python opencv 教程
- python格式化转换_Python进制转换format格式化[通俗易懂]
- python中bool函数_bool()函数以及Python中的示例
- python海龟作图红绿灯_海龟作图—用Python绘图
- Python 监控linux之dstat
- python黑帽子一netcat
- 【Python】python文件打开方式详解——a、a+、r+、w+、rb、rt区别[通俗易懂]
- 【说站】python中Harris角点检测
- python 路径管理以及常见报错
- Python标识符的命名规则,下列哪些是对的?_python标识符不能使用关键字
- python分析人口出生率代码_国家统计局居然也能用的上Python?人口数据Python脚本了解一下?…[通俗易懂]
- Python常看函数用法,返回值类型
- python抛出异常和捕获异常_Python异常
- java rpc接口_java调用python模型
- Neural Compressor:用于模型压缩的开源 Python 库
- Python 抓取并解码原始数据包
- Python-3.11.2 发布了!!!
- Python 数据类型详细篇:列表
- PCA、SVD深入浅出与python代码
- python 报错信息
- python-Python与MongoDB数据库-使用Python执行MongoDB查询(三)
- Linux创建Python文件的步骤(linux新建python文件)
- 开发Linux下Python编程:实现自己的开发梦想(linux下python)
- Python @property装饰器详解
- python使用Python轻松操作Redis(redis-)
- Python实现快速连接Redis数据库(python连接redis)
- python驱动使用pip安装MySQL Python驱动的简单步骤(pip安装mysql)
- 一篇文章教你用 11 行 Python 代码实现神经网络