python函数参数中的*args与**kw的区别

2020-03-27  本文已影响0人  猪猪一号
if __name__ == '__main__':
    astr = "ABC"
    alist = [1, 2, 3]
    adict = {"name": "wangbm", "age": 18}
    # generate
    agen = (i for i in range(4, 8))

    def gen(*args, **kw):
        print("the type of *args is ",type(args))        
        print("the content of *args is:")
        print(args)   
        print("type of **kw is ",type(kw))        
        print("the content of **kw is:")
        print(kw)
        for item in args:             
            for i in item:
                yield i

    new_list = gen(astr, alist, adict, agen,ab = 'lbsjs',pang = 'yang')
    print(list(new_list))
the type of *args is  <class 'tuple'>
the content of *args is:
('ABC', [1, 2, 3], {'name': 'wangbm', 'age': 18}, <generator object <genexpr> at 0x000001ECBF380EC8>)
type of **kw is  <class 'dict'>
the content of **kw is:
{'ab': 'lbsjs', 'pang': 'yang'}
['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]

*arge将所有类型的变量全部make成一个tuple.
**kw只接收关键字参数(这类参数可以在调用函数时无视函数参数的顺序)例如:
ab = 'lbsjs',pang = 'yang',然后把这个参数make成一个dict.

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
上一篇 下一篇

猜你喜欢

热点阅读