默认参数是在函数调用时,没有为参数提供值,而是使用预先定义的默认值。形参的格式为“para_name=default_value”。Python中用默认值声明变量的语法是所有的位置参数必须出现在任何一个默认参数之前。
def function_name(position_para1,default-para=default_value1,…..):
“函数说明注释” #python的注释方法
function body
return return_values
调用函数时可传可不传该默认参数的值。
默认参数的值仅仅在函数定义的时候赋值一次。再次赋值时将不起作用。如
>>> x=42
>>> defspam(a,b=x):
print(a,b)
>>> spam(1)
1 42
>>> x=43 #不起作用
>>> spam(1)
1 42
>>>
默认参数的值应该是不可变的对象,比如None、True、False、数字或字符串。如果默认参数是一个可修改的容器比如一个列表、集合或者字典,往往引起问题。因为在这种情况下参数可以在不创建新对象的情况下进行修改。如
>>> deffunc(data=[]):
... data.append(1)
... return data
...
>>> func()
[1]
>>> func()
[1, 1]
>>> func()
[1, 1, 1]
"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 the same “pre-computed”value is used for each call. This is especially important to understand when adefault parameter is a mutable object, such as a list or a dictionary: if thefunction modifies the object (e.g. by appending an item to a list), the defaultvalue is in effect modified. This is generally not what was intended.
这就是以可变对象作为默认参数的编程陷进,再比如,
>>> classQueEle():
... def __init__(self,fpath=[],cur=None):
... self.fpath=fpath
... self.cur=cur
...
>>>
>>> for iin range(3):
... qe=QueEle()
... qe.fpath.append((1,2))
... print qe.fpath
...
[(1, 2)]
[(1, 2), (1, 2)]
[(1, 2), (1, 2), (1,2)]
>>>
这里有两个解决方法,一是使用None作为默认值;二是在函数中使用list对实参做一份拷贝,避免共享,如
>>> deffunc2(data=[]):
... ele=list(data)
... ele.append(1)
... return ele
...
>>> func2()
[1]
>>> func2()
[1]
>>> classQueEle():
... def __init__(self,fpath=[],cur=None):
... self.fpath=list(fpath)
... self.cur=cur
...
>>> for iin range(3):
... qe=QueEle()
... qe.fpath.append((1,2))
... print qe.fpath
...
[(1, 2)]
[(1, 2)]
[(1, 2)]
>>>
网友评论