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}
  • 相关阅读:
    V4L2 soccamera 子系统
    ubuntu10.04 vim 配置
    Video for Linux Two
    I2C总线的仲裁机制
    Android Camera 通过V4L2与kernel driver的完整交互过程
    ubuntu安装辞典
    v4l2 camera 驱动架构 之 isp controller 驱动
    Android Camera 运行流程
    CentOS 7.x安装图文示范
    同余与模运算
  • 原文地址:https://www.cnblogs.com/liangmingshen/p/9251047.html
Copyright © 2011-2022 走看看