python中的*args 和 **kwargs
1. 簡介
- args 是 arguments 的縮寫,表示位置參數;
- kwargs 是 keyword arguments 的縮寫,表示關鍵字參數.
- *args 必須放在 **kwargs 的前面.
- args 和 kwargs 可以不是這兩個字幕, 只是約定俗成.
- *args 和 **kwargs 主要用於函數定義。 你可以將不定數量的參數傳遞給一個函數
2. 用法
- 2.1 * args 用法
*ags 是用來發送一個非鍵值對的可變數量的參數列表給一個函數.
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')
輸出爲:
first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test
- 2.2 ** kwargs 用法
**kwargs 允許你將不定長度的鍵值對, 作爲參數傳遞給一個函數。 如果你想要在一個函數裏處理帶名字的參數, 你應該使用**kwargs。
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} == {1}".format(key, value))
>>> greet_me(name="yasoob")
name == yasoob
- 2.3 和標準參數一起作爲函數參數
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
# 首先使用 *args
>>> args = ("two", 3, 5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5
# 現在使用 **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3