感謝作者和譯者,向你們致敬,辛苦了!
文章地址:Python進階
args 和 kwargs
*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')
輸出內容:
first normal arg: yasoob
another arg through *argv: python
another arg through *argv: eggs
another arg through *argv: test
**kwargs 允許你將不定長度的鍵值對, 作為參數(shù)傳遞給一個函數(shù)。
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} == {1}".format(key, value))
greet_me(name="yasoob")
輸出內容:
name == yasoob
使用 *args 和 **kwargs 來調用函數(shù)
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
args = ("two", 3, 5)
test_args_kwargs(*args)
print("---")
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)
輸出內容:
arg1: two
arg2: 3
arg3: 5
---
arg1: 5
arg2: two
arg3: 3
什么時候使用它們?
做測試時,可以把API調用替換成一些測試數(shù)據(jù)
import someclass
def get_info(self, *args):
return "Test data"
someclass.get_info = get_info