• [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.

  • 相关阅读:
    抓包来看ftp状态码
    socket基础篇
    密码复杂度检查函数
    time模块
    读取日志文件,搜索关键字,打印关键字前5行。yield、deque实例
    装饰器--函数
    yield用法
    字符编码
    pycharm + git实现两台电脑代码同步
    PyCharm常见用法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7906368.html
Copyright © 2020-2023  润新知