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)、使用条件判断

  • 相关阅读:
    spring整合myBatis
    spring之事物
    spring之AspectJ实现AOP
    AOP之JDK动态代理和CGLib动态代理
    iOS-面试相关<一>
    iOS -调试工具Instruments使用总结
    iOS-阅读器常年崩溃问题记录
    iOS
    ios
    iOS
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14504666.html
Copyright © 2011-2022 走看看