zoukankan      html  css  js  c++  java
  • python中的*arg和**kwargs

    arg对应多出来的位置参数,把它们解析成tuple;kwargs把关键字参数解析成dict.

    def example(pram):
        print(pram)
    
    
    def example2(param, *args, **kwargs):
        print(param)
        if args:
            print(args)
        if kwargs:
            print(kwargs)
    
    
    #一个不设定参数个数的加法函数
    def sum(*args):
        sum = 0
        for a in args:
            sum += a
        return sum
    
    
    #控制关键字参数的个数,可以用"*"作为分割参数
    def person(param, *, keyword1, keyword2):
        print(param, keyword1, keyword2)
    
    
    ############################################3
    #反向思维用法
    def another_sum(a, b, c):
        print(a + b + c)
    
    if __name__ == "__main__":
        example("hello world!")    #hello world!
        #该情况下会报错
        # example("hello world!", "honey")
    
        #*args, **kwargs为空也不行影响函数运行
        example2("hello world!")    #hello world!
    
        #pram是位置参数;*arg会把多的位置参数转成元组;**kwargs必须要带上关键字,比如"word1=",关键字参数会被转成字典.
        example2("hello world!", "honey", "hi", word1="happy new year", word2="red packet") #hello world!
                                                                                                     #('honey', 'hi')
                                                                                                     #{'word1': 'happy new year', 'word2': 'red packet'}
    
        # 一个不设定参数个数的加法函数
        print(sum(1, 2, 3, 4))  #10
    
        # 控制关键字参数的个数
        person("name:", keyword1="qin", keyword2="fen") #name: qin fen
    
        ############################################3
        # 反向思维
        arg1 = [1, 2, 3]
        #把lis进行了拆分
        another_sum(*arg1)    #6
    
        #此处的键要和形参一致,必须为'a','b','c'
        kwargs1 = {"a":1, "b":2, "c":3}
        another_sum(**kwargs1)    #6

    文章参考:https://www.jianshu.com/p/e0d4705e8293

    新战场:https://blog.csdn.net/Stephen___Qin
  • 相关阅读:
    微软 安全用户教育影片 有MM 哦
    数据字典是什么?
    调用Object.GetHashCode的缺省实现
    CCharp 中委托和事件的机制和应用
    C#.NET 中的类型转换
    解决在全文搜索中搜索中文字符
    ADO.NET 获取大型 数据
    Realize the Potential of Office 2003 by Creating Smart Tags in Managed Code
    MSDN 智能客户端开发人员中心
    ADO.Net 缓冲 插入大型数据
  • 原文地址:https://www.cnblogs.com/Stephen-Qin/p/10326254.html
Copyright © 2011-2022 走看看