本節討論Python下函數型參的預設值問題。
Python在設計函數時,可以給型參預設缺省值,當用戶調用函數時可以不輸入實參。如果用戶不想使用缺省預設值則需要給型參一一賦值,可以給某些型參賦值或不按型參順序用表達式給型參賦值,說起來有些繞,我們看看例子好了!
#define function: area with two args
def area(width = 10, height = 10):
z = width * height
print(z)
#define fucntion: main
def main():
#call function area
print("prototype: area(width = 10, height = 10):")
print("area()")
area()
print("area(20)")
area(20)
print("area(width = 20)")
area(width = 20)
print("area(height = 30)")
area(height = 30)
print("area(20, 30)")
area(20, 30)
print("area(height = 30, width = 30)")
area(height = 30, width = 30)
#entry of programme
main()
代碼第2~4行是採用預設型參值的方式定義了一個函數area。好處是在函數調用時可以不輸入實參(第11行),用戶函數調用時可以依據自己的需求修改或者說傳入型參(第13行改變了width的值,而height的值仍使用預設值)(第19行,修改width的值爲20,height的值爲30),當然也可以不按型參順序賦值(第21行),程序運行結果如下。
prototype: area(width = 10, height = 10):
area()
100
area(20)
200
area(width = 20)
200
area(height = 30)
300
area(20, 30)
600
area(height = 30, width = 30)
900
呵呵