Optional parameters in Python functions and their default values [duplicate]

≯℡__Kan透↙ 提交于 2019-11-30 05:40:28

Good doc from PyCon a couple years back - Default parameter values explained. But basically, since lists are mutable objects, and keyword arguments are evaluated at function definition time, every time you call the function, you get the same default value.

The right way to do this would be:

def F(a, b=None):
    if b is None:
        b = []
    b.append(a)
    return b
Jonas Elfström

Default parameters are, quite intuitively, somewhat like member variables on the function object.

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

http://docs.python.org/reference/compound_stmts.html#function

Lists are a mutable objects; you can change their contents. The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function:

def good_append(new_item, a_list=None):
    if a_list is None:
        a_list = []
    a_list.append(new_item)
    return a_list
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!