python 中*args 和 **kwargs的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sty945/article/details/79490822

*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的用法:

  1. enumerate()是python的内置函数
  2. enumerate在字典上是枚举、列举的意思
  3. 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
  4. 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

猜你喜欢

转载自blog.csdn.net/sty945/article/details/79490822
今日推荐