*args 的用法
*args 和 **kwargs 主要用于函數(shù)定義。 你可以將不定數(shù)量的參數(shù)傳遞給一個函數(shù)纵装。
這里的不定的意思是:預(yù)先并不知道, 函數(shù)使用者會傳遞多少個參數(shù)給你, 所以在這個場景下使用這兩個關(guān)鍵字骑脱。 *args 是用來發(fā)送一個非鍵值對的可變數(shù)量的參數(shù)列表給一個函數(shù).
這里有個例子幫你理解這個概念:
def test_var_args(f_arg, *argv):
print("first normal arg:", f_arg)
for arg in argv:
print("another arg through *argv:", arg)
test_var_args('yasoob', 'python', 'eggs', 'test')
這會產(chǎn)生如下輸出:
first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test
**kwargs 的用法
kwargs 允許你將不定長度的鍵值對, 作為參數(shù)傳遞給一個函數(shù)拳昌。 如果你想要在一個函數(shù)里處理帶名字的參數(shù), 你應(yīng)該使用kwargs。
這里有個讓你上手的例子:
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} == {1}".format(key, value))
>>> greet_me(name="yasoob")
name == yasoob
現(xiàn)在你可以看出我們怎樣在一個函數(shù)里, 處理了一個鍵值對參數(shù)了。
這就是******kwargs的基礎(chǔ), 而且你可以看出它有多么管用鸵荠。 接下來讓我們談?wù)劊阍鯓邮褂?*****args 和 ******kwargs來調(diào)用一個參數(shù)為列表或者字典的函數(shù)伤极。
使用 ******args 和 ******kwargs 來調(diào)用函數(shù)
那現(xiàn)在我們將看到怎樣使用args和*kwargs 來調(diào)用一個函數(shù)蛹找。 假設(shè),你有這樣一個小函數(shù):
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
你可以使用args或*kwargs來給這個小函數(shù)傳遞參數(shù)哨坪。 下面是怎樣做:
首先使用 *args
>>> args = ("two", 3, 5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5
現(xiàn)在使用 **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3
標(biāo)準(zhǔn)參數(shù)與args庸疾、*kwargs在使用時的順序
那么如果你想在函數(shù)里同時使用所有這三種參數(shù), 順序是這樣的:
some_func(fargs, *args, **kwargs)
什么時候使用它們当编?
這還真的要看你的需求而定届慈。
最常見的用例是在寫函數(shù)裝飾器的時候(會在另一章里討論)。
此外它也可以用來做猴子補(bǔ)丁(monkey patching)忿偷。猴子補(bǔ)丁的意思是在程序運(yùn)行時(runtime)修改某些代碼金顿。 打個比方,你有一個類牵舱,里面有個叫g(shù)et_info的函數(shù)會調(diào)用一個API并返回相應(yīng)的數(shù)據(jù)串绩。如果我們想測試它,可以把API調(diào)用替換成一些測試數(shù)據(jù)芜壁。例如:
import someclass
def get_info(self, *args):
return "Test data"
someclass.get_info = get_info
我敢肯定你也可以想象到一些其他的用例礁凡。