python的*args與**kwargs

來源:互聯網
上載者:User

標籤:AC   *args   ast   字典   erro   ror   錯誤   font   允許   

1. *args 允許將一個非索引值對的可變數量的參數列表(元組)傳遞給一個函數。

>>> def add(*args):...     return sum(args)...>>> add(1,2,3,4)10>>> a = (1,2,3,4)>>> add(a) # 錯誤,等價於sum(((1,2,3,4),)),即將元組a與0相加Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 2, in addTypeError: unsupported operand type(s) for +: ‘int‘ and ‘tuple‘>>> add(*a)10>>> sum(((1,2,3,4),))Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for +: ‘int‘ and ‘tuple‘

 

2. **kwargs 允許將一個索引值對的可變數量的參數字典傳遞給一個函數。

>>> def add(**kwargs):...     return sum(kwargs.values())...>>> add(a=1,b=2,c=3)6

 

綜合:

>>> def f(arg,*args,**kwargs):...     print(arg)...     print(args)...     print(kwargs)...>>> f(1,*(1,2,3,4),**{"a":1,"b":2,"c":3})1(1, 2, 3, 4){‘b‘: 2, ‘c‘: 3, ‘a‘: 1}>>> f(1,1,2,3,4,a=1,b=2,c=3) # 與上面效果一樣

 

 

調用時

def func(a,b,c,d):    print(a,b,c,d)args = (1,2,3,4)func(*args)1,2,3,4def func(a,b,c,d):    print(a,b,c,d)kargs = {‘a‘:1, ‘b‘:2, ‘c‘:3, ‘d‘:4}func(**kargs)1,2,3,4

 

python的*args與**kwargs

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.