
上QQ阅读APP看书,第一时间看更新
4.9 默认参数值
定义函数时,可以指定参数具有默认值。调用函数时,如果不给带默认值的参数传递默认值,该参数将自动使用它的默认值。下面的代码用默认参数值定义函数rectangle_area
:

通过让参数名后跟一个“=
”和一个值来指定默认的参数值。在本例中,length
的默认参数值是2,width
的默认参数值是3。参数列表中,任何具有默认值的参数必须在没有默认值的参数的右侧。
下面的代码调用函数rectangle_area
时没有参数,因此IPython会使用两个默认参数值来执行函数,相当于以rectangle_area(2,3)
的形式调用函数:

下面的代码在调用函数rectangle_area
时只给出一个参数。参数的赋值顺序为从左到右,所以10传给了参数length
,参数width
则使用默认值3,相当于以rectangle_area(10,3)
的形式调用函数:

下面的代码调用rectangle_area
时给出了length
和width
两个参数的值,所以IPython会忽略掉默认参数:
