當要使函數接收元組或字典形式的參數的時候,有一種特殊的方法,它分別使用*和**前綴。
這種方法在函數需要獲取可變數量的參數的時候特別有用。
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
由于在args變量前有*前綴,所有多余的函數參數都會作為一個元組存儲在args中。如果使用的
是**前綴,多余的參數則會被認為是一個字典的鍵/值對。
這種方法在函數需要獲取可變數量的參數的時候特別有用。
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
由于在args變量前有*前綴,所有多余的函數參數都會作為一個元組存儲在args中。如果使用的
是**前綴,多余的參數則會被認為是一個字典的鍵/值對。