zoukankan      html  css  js  c++  java
  • python中将实参变成可选的

    1、

    >>> def a(x,y,z):
        print(x + y + z)
    
        
    >>> a(2,3,4)
    9
    >>> a(2,3)         ## 缺少对应的实参
    Traceback (most recent call last):
      File "<pyshell#317>", line 1, in <module>
        a(2,3)
    TypeError: a() missing 1 required positional argument: 'z'
    >>> def a(x,y,z = ""):   ## 将z设为空
        print(x + y + z)
    
        
    >>> a(2,3,4)
    9
    >>> a(2,3)       ## 缺少对应实参
    Traceback (most recent call last):
      File "<pyshell#322>", line 1, in <module>
        a(2,3)
      File "<pyshell#320>", line 2, in a
        print(x + y + z)
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    >>> def a(x,y,z = ""):      ## 将z设为空,同时使用条件判断
        if z:
            print(x + y + z)
        else:
            print(x + y)
    
            
    >>> a(2,3,4)
    9
    >>> a(2,3)
    5
    >>> def a(x,y,z):      ## 未将z设为空,使用条件判断
        if z:
            print(x + y + z)
        else:
            print(x + y)
    
            
    >>> a(2,3,4)
    9
    >>> a(2,3)
    Traceback (most recent call last):
      File "<pyshell#334>", line 1, in <module>
        a(2,3)
    TypeError: a() missing 1 required positional argument: 'z'

    将实参设为可选的两个条件:

    (1)、在形式参数中指定为空

    (2)、使用条件判断

  • 相关阅读:
    树世界
    清空 NumericUpDown
    没有评论的日子
    GetData.cs

    Hashtable 在程序中控制重复项
    Convert.ToInt32() VS System.Int32.Parse()
    饮食九要素
    添加 or 修改 的一个处理方式
    一个关于 电话号码 的正则表达式
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14504666.html
Copyright © 2011-2022 走看看