Python方法参数(*args, **kwargs)总结

刚开始学习python的时候,对有关args,kwargs,和*的使用感到很困惑。相信对此感到疑惑的人也有很多。我打算通过这个帖子来排解这个疑惑(希望能减少疑惑)。

  • *args表示任何多个无名参数,它是一个tuple
  • **kwargs:传入的字典,就如:a=1,传入键值

传入元组,args表示成一个元组

def param_tuple(*args):
    print(type(args))
    print(args)
    for value in args:
        print(value)
    for key,value in enumerate(args):
        print("{0}->{1}".format(key,value))
param_tuple(1,2,43)

输出结果为:


(1, 2, 43)
1
2
43
0->1
1->2
2->43

传入元组给**kwargs会报错

def param_tuple(**kargs):
    print(type(kargs))
    print(kargs)

param_tuple(1,2,43)

输出结果为:

发生异常: TypeError
param_tuple() takes 0 positional arguments but 3 were given

参数中传入字典, **kwargs表示成一个字典

def param_tuple(**kargs):
    print(type(kargs))
    print(kargs)
    for key,value in enumerate(kargs):
        print("{0}->{1}".format(key,value))
param_tuple(a = 1, b = 2, c = 43)

输出结果为:


{'a': 1, 'b': 2, 'c': 43}
0->a
1->b
2->c

函数的参数中混用tuple和dic

def param_tuple_dic(*args, **kwargs):
    print(type(args))
    print(type(kwargs))
        
    print(args)
    print(kwargs)
    for value in args:
        print(value)
    for key ,value in kwargs.items():
        print("{0}==>{1}".format(key,value))

param_tuple_dic("1","2","43", a = 1, b = 2, c = 43)

输出结果为:



('1', '2', '43')
{'a': 1, 'b': 2, 'c': 43}
1
2
43
a==>1
b==>2
c==>43

你可能感兴趣的:(Python方法参数(*args, **kwargs)总结)