zoukankan      html  css  js  c++  java
  • Python 不定参数函数

    1. 元组形式

    def test1(*args):
    
        print('################test1################')
        print(type(args))
        print(args)

    正确调用:

    test1(1, 2)          #args在函数体内部为tuple类型

    错误调用:

    test1(1, b=2)      #TypeError: test1() got an unexpected keyword argument 'b'
    test1(a=1, b=2)  #TypeError: test1() got an unexpected keyword argument 'a'
    test1(a=1, 2)      #TypeError: test1() got an unexpected keyword argument 'a'

    2. 字典形式

    def test2(**kargs):
    
        print('################test2################')
        print(type(kargs))
        print(kargs)

    正确调

    test2(a=1, b=2)  #kargs在函数体内部为dict类型

    错误调用:

    test2(1, 2)          #TypeError: test2() takes exactly 0 arguments (2 given)
    test2(1, b=2)      #TypeError: test2() takes exactly 0 arguments (2 given)
    test2(a=1, 2)      #SyntaxError: non-keyword arg after keyword arg

    3. 混合形式

    def test3(*args, **kargs):
    
        print('################test3################')
        print(type(args))
        print(args)
        print(type(kargs))
        print(kargs

    正确调用:

    test3(1, 2)          #args在函数体内部为tuple类型,kargs为空dict类型
    test3(1, b=2)      #args在函数体内部为tuple类型,kargs为dict类型
    test3(a=1, b=2)  #args在函数体内部为空tuple类型,kargs为dict类型

    错误调用:

    test3(a=1, 2)      #SyntaxError: non-keyword arg after keyword arg

     练习:

    1 def test(num,*args,**kwargs):
    2     print('---test1---%d' %num)
    3     print('---test2---',args)
    4     print('---test3---',kwargs)
    5 
    6 test(100)
    7 test(100,200)
    8 test(100,200,300,mm=100)

    答案:

     1 C:>python test.py
     2 ---test1---100
     3 ---test2--- ()
     4 ---test3--- {}
     5 
     6 ---test1---100
     7 ---test2--- (200,)
     8 ---test3--- {}
     9 
    10 ---test1---100
    11 ---test2--- (200, 300)
    12 ---test3--- {'mm': 100}
  • 相关阅读:
    09课堂问题整理
    08课堂问题整理
    Eclipse开发工具的编码问题
    【伸手党】需要我帮你Google/百度吗?
    IDEA更改左侧目录层级结构
    IDEA设置类和方法的注释
    一篇系列
    "Notice: unserialize(): Error at offset xx of xxx bytes"错误的处理(转载)
    git push命令每次都要输入用户名和密码的问题处理
    在网站添加qq客服功能
  • 原文地址:https://www.cnblogs.com/liangmingshen/p/9251047.html
Copyright © 2011-2022 走看看