Python中,(*)會把接收到的參數形成一個元組,而(**)則會把接收到的參數存入一個字典
我們可以看到,foo方法可以接收任意長度的參數,並把它們存入一個元組中
>>> def foo(*args):
... print(args)
...
>>> foo("fruit", "animal", "human")
('fruit', 'animal', 'human')
>>> foo(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)
>>> arr = [1, 2, 3, 4, 5] # 如果我們希望將一個數組形成元組,需要在傳入參數的前面 加上一個*
>>> foo(arr)
([1, 2, 3, 4, 5],)
>>> foo(*arr)
(1, 2, 3, 4, 5)
(**)將接收到的參數存入一個字典
>>> def foo(**kwargs):
... for key, value in kwargs.items():
... print("%s=%s" % (key, value))
...
>>> foo(a=1, b=2, c=3)
a=1
b=2
c=3
(*)和(**)一起使用
>>> def foo(*args, **kwargs):
... print("args:", args)
... print("kwargs:", kwargs)
...
>>> foo(1, 2, 3, a=1, b=2)
args: (1, 2, 3)
kwargs: {'a': 1, 'b': 2}
>>> arr = [1, 2, 3]
>>> foo(*arr, a=1, b=2)
args: (1, 2, 3)
kwargs: {'a': 1, 'b': 2}
name作為foo第一個參數,在調用foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)方法時,自然而然捕獲了hello,而middle必須經過指定關鍵字參數才可以捕獲值,否則會和之前的參數一樣形成一個元組
>>> def foo(name, *args, middle=None, **kwargs):
... print("name:", name)
... print("args:", args)
... print("middle:", middle)
... print("kwargs:", kwargs)
...
>>> foo("hello", 1, 2, 3, a=1, b=2, c=3)
name: hello
args: (1, 2, 3)
middle: None
kwargs: {'a': 1, 'b': 2, 'c': 3}
>>> foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)
name: hello
args: (1, 2, 3)
middle: world
kwargs: {'a': 1, 'b': 2, 'c': 3}
>>> my_foo = {"name": "hello", "middle": "world", "a": "1", "b": "2", "c": "3"}
>>> foo(**my_foo)
name: hello
args: ()
middle: world
kwargs: {'a': '1', 'b': '2', 'c': '3'}
此外,我們還可以定義一個字典my_foo,並以foo(**my_foo)這樣的方式,讓name和middle各自捕獲自己的值,沒有捕獲的則存入一個字典
當我們刪除my_foo中的name,再像之前傳入函數,函數會報錯說需要name這個參數
>>> del my_foo["name"] >>> foo(**my_foo) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() missing 1 required positional argument: 'name'
