美文网首页
python函数参数中的*args与**kw的区别

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

作者: 猪猪一号 | 来源:发表于2020-03-27 09:58 被阅读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")
    

    相关文章

      网友评论

          本文标题:python函数参数中的*args与**kw的区别

          本文链接:https://www.haomeiwen.com/subject/jawkuhtx.html