Python中*和**的區別

Python中,(*)會把接收到的參數造成一個元組,而(**)則會把接收到的參數存入一個字典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

 

(*)和(**)一塊兒使用 ui

>>> 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必須通過指定關鍵字參數才能夠捕獲值,不然會和以前的參數同樣造成一個元組blog

>>> 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各自捕獲本身的值,沒有捕獲的則存入一個字典it

 

當咱們刪除my_foo中的name,再像以前傳入函數,函數會報錯說須要name這個參數io

>>> 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'
相關文章
相關標籤/搜索