*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
我希望這解決了你所有的困惑. 那接下來讓我們談?wù)?**kwargs