编程语言
首页 > 编程语言> > python中将实参变为可选项

python中将实参变为可选项

作者:互联网

 

1、

>>> def a(first,meddle,last):
    b = f"{first} {meddle} {last}"
    return b.title()

>>> a("aaa","bbb","ccc")
'Aaa Bbb Ccc'
>>> a("aaa","bbb")   ## 少一个实参报错
Traceback (most recent call last):
  File "<pyshell#159>", line 1, in <module>
    a("aaa","bbb")
TypeError: a() missing 1 required positional argument: 'last'
>>> def a(first,last,meddle = ""):    ## 将一个实参设定为空
    b = f"{first} {meddle} {last}"
    return b.title()

>>> a("aaa","bbb","ccc")
'Aaa Ccc Bbb'
>>> a("aaa","ccc")
'Aaa  Ccc'
>>> def a(first,last,meddle = None):   ## 讲一个实参设定为None , None等价于 “”。
    b = f"{first} {meddle} {last}"
    return b.title()

>>> a("aaa","ccc","bbb")
'Aaa Bbb Ccc'
>>> a("aaa","ccc")
'Aaa None Ccc'

 

>>> def a(first,meddle,last):
    b = f"{first} {meddle} {last}"
    return b.title()

>>> a("aaa","bbb","ccc")
'Aaa Bbb Ccc'
>>> a("aaa","ccc")      ## 少一个实参,报错
Traceback (most recent call last):
  File "<pyshell#171>", line 1, in <module>
    a("aaa","ccc")
TypeError: a() missing 1 required positional argument: 'last'

 

标签:aaa,python,bbb,可选项,last,实参,meddle,ccc,first
来源: https://www.cnblogs.com/liujiaxin2018/p/14510515.html