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

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14504666.html