當前位置:
首頁 >
python 中*args 和 **kwargs的区别
發布時間:2023/11/28
40
豆豆
生活随笔
收集整理的這篇文章主要介紹了
python 中*args 和 **kwargs的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
*args的用法
當你不確定你的函數里將要傳遞多少參數時你可以用*args.例如,它可以傳遞任意數量的參數:
def print_everything(*args):for count, thing in enumerate(args):print('{0}.{1}'.format(count, thing))print_everything('apple', 'banana', 'cabbage')
output:
0.apple
1.banana
2.cabbage
順便提一下enumerate的用法:
- enumerate()是python的內置函數
- enumerate在字典上是枚舉、列舉的意思
- 對于一個可迭代的(iterable)/可遍歷的對象(如列表、字符串),enumerate將其組成一個索引序列,利用它可以同時獲得索引和值
- enumerate多用于在for循環中得到計數
實例
list1 = ["hello", "world", "hello", "china"]
for i in range (len(list1)):print(i ,list1[i])
output
0 hello
1 world
2 hello
3 china
但是用enumerate也可以得到同樣的效果, 并且更加美觀:
list1 = ["hello", "world", "hello", "china"]
for index, value in enumerate(list1):print(index, value)
output:
0 hello
1 world
2 hello
3 china
enumerate**還可以接收第二個參數**,用于指定索引起始值,如:
list1 = ["hello", "world", "hello", "china"]
for index, value in enumerate(list1, 1):print(index, value)
output:
1 hello
2 world
3 hello
4 china
**kwargs的用法
相似的,**kwargs允許你使用沒有事先定義的參數名:
def table_things(**kwargs):for name, value in kwargs.items():print('{0}={1}'.format(name, value))
table_things(apple='fruit', cabbage='vegetable')
output:
apple=fruit
cabbage=vegetable
例外
你也可以混著用.命名參數首先獲得參數值然后所有的其他參數都傳遞給*args和**kwargs.命名參數在列表的最前端.例如:
def table_things(titlestring, **kwargs)
*args和**kwargs可以同時在函數的定義中,但是*args必須在**kwargs前面.
當調用函數時你也可以用*和***語法.例如:
def print_three_things(a, b, c):print('a = {0}, b = {1}, c = {2}'.format(a, b, c))
mylist = ['apple', 'banana', 'china']
print_three_things(*mylist)
output:
a = apple, b = banana, c = china
就像你看到的一樣,它可以傳遞列表(或者元組)的每一項并把它們解包.注意必須與它們在函數里的參數相吻合.當然,你也可以在函數定義或者函數調用時用*.
參考:
http://stackoverflow.com/questions/3394835/args-and-kwargs
轉載請注明出處:
CSDN:樓上小宇__home:http://blog.csdn.net/sty945
總結
以上是生活随笔為你收集整理的python 中*args 和 **kwargs的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中__dict__与dir(
- 下一篇: python中的新式类与旧式类的一些基于