Optional parameters in Python functions and their default values
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm kind of confused about how optional parameters work in Python functions/methods.
I have the following code block:
>>> def F(a, b=[]):
... b.append(a)
... return b
...
>>> F(0)
[0]
>>> F(1)
[0, 1]
>>>
Why F(1)
returns [0, 1]
and not [1]
?
I mean, what is happening inside ?
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
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 (eg 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
链接地址: http://www.djcxy.com/p/28520.html
上一篇: python函数的默认参数只评估一次?
下一篇: Python函数中的可选参数及其默认值