各種語言都有它自己特定的函數(shù)參數(shù)定義方法。Python語言對于函數(shù)參數(shù)的定義非常靈活,它提供了三種定義函數(shù)參數(shù)的方式。一起來看看吧,希望對大家學(xué)習(xí)python有所幫助。
1. Positional arguments位置參數(shù)
這是Python中最簡單的給函數(shù)傳遞參數(shù)的方式。當(dāng)調(diào)用函數(shù)時,調(diào)用代碼中的函數(shù)參數(shù)與函數(shù)定義時的參數(shù)的順序一致。例如:
>>> defpower(x, y):... r = 1... while y > 0:... r = r * x... y = y - 1... return r... >>> power(3, 4)27
上述代碼中,調(diào)用函數(shù)時3->x,4->y。也可以在定義函數(shù)時,給函數(shù)參數(shù)指定默認(rèn)值,類似于下面這樣:
def fun(arg1, arg2=default2, arg3=default3, . . .)
包含有默認(rèn)值的函數(shù)參數(shù),必須在函數(shù)參數(shù)列表的最后面的位置。如果上面的函數(shù)定義中arg1也包含默認(rèn)值的話,所有后面的參數(shù)都應(yīng)該包含默認(rèn)值。
在調(diào)用時,如果沒有指定帶默認(rèn)值的函數(shù)參數(shù),則使用參數(shù)中的默認(rèn)值。例如調(diào)用上面的函數(shù)時,通過fun(1)這種方式調(diào)用時,1->arg1,arg2=default2,arg3=default3;通過fun(1,2,3)這種方式調(diào)用時,1->arg1,2->arg1,3->arg3。
2. Keyword arguments關(guān)鍵字參數(shù)
可以在調(diào)用函數(shù)時,使用相應(yīng)函數(shù)參數(shù)的名稱來傳遞參數(shù)。例如還是上面power函數(shù)的定義,在調(diào)用時,通過如下方式:
>>> power(y=2, x=3)9
上面的函數(shù)調(diào)用,因為使用了函數(shù)參數(shù)的名稱來傳遞參數(shù),所以參數(shù)的位置便無關(guān)緊要了。
3. Variable-length argument可變數(shù)量參數(shù)
Python的函數(shù)也可以處理可變數(shù)量的函數(shù)參數(shù)??梢杂袃煞N方式:
3.1. 處理任意數(shù)目的位置參數(shù)
在函數(shù)的參數(shù)列表中,最后一個參數(shù)前添加一個 * 號,便可以將傳入該函數(shù)的多余的參數(shù)存在以該參數(shù)命名的元組中。例如,有如下函數(shù)定義:
>>> def maximum(*numbers):... if len(numbers) == 0:... return None... else:... maxnum = numbers[0]...for n in numbers[1:]:... if n > maxnum:... maxnum = n... return maxnum
通過如下方式調(diào)用:
>>> maximum(3, 2, 8)8>>> maximum(1, 5, 9, -2, 2)9
3.2. 處理任意數(shù)目的關(guān)鍵字參數(shù)
在函數(shù)的參數(shù)列表中,最后一個參數(shù)前添加一個 ** 號,便可以將傳入該函數(shù)的多余的關(guān)鍵字參數(shù)存在以該參數(shù)命名的字典中。例如,有如下函數(shù)定義:
>>> def example_fun(x, y, **other):... print("x: {0}, y: {1}, keys in 'other': {2}".format(x, ... y, list(other.keys())))... other_total = 0... for k in other.keys():... other_total = other_total + other[k]... print("The total of values in 'other' is {0}".format(other_total))
通過如下方式調(diào)用:
>>> example_fun(2, y="1", foo=3, bar=4)x: 2, y: 1, keys in 'other': ['foo', 'bar']
The total of values in 'other' is 7
4. Mixing argument-passing techniques混合參數(shù)
可以混合上面的3種方式定義函數(shù),只要可變長度的函數(shù)參數(shù)定義在函數(shù)參數(shù)列表的最后。例如:
# Accept variable number of positional or keyword argumentsdef spam(*args, **kwargs):
# args is a tuple of positional args
# kwargs is dictionary of keyword args
...
來源:Andy's Techblog