有没有办法将可选参数传递给函数?

Python中有没有一种方法可以在调用函数时将可选参数传递给函数,并且函数定义中的代码基于“仅当传递了可选参数时”



隔江千里
浏览 490回答 3
3回答

精慕HU

在Python 2中的文档,7.6。函数定义为您提供了两种方法来检测调用方是否提供了可选参数。首先,您可以使用特殊的形式参数语法*。如果函数定义的形式参数前面带有single *,则Python会使用前形式参数(作为元组)不匹配的任何位置参数填充该参数。如果函数定义的正式参数以开头**,则Python会使用与先前正式参数不匹配的任何关键字参数(作为dict)来填充该参数。函数的实现可以检查这些参数的内容,以查找所需的任何“可选参数”。例如,这是一个函数opt_fun,它接受两个位置参数x1和x2,并寻找另一个名为“ optional”的关键字参数。>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):...     if ('optional' in keyword_parameters):...         print 'optional parameter found, it is ', keyword_parameters['optional']...     else:...         print 'no optional parameter, sorry'... >>> opt_fun(1, 2)no optional parameter, sorry>>> opt_fun(1,2, optional="yes")optional parameter found, it is  yes>>> opt_fun(1,2, another="yes")no optional parameter, sorry其次,您可以提供None某个调用者将永远不会使用的默认参数值。如果参数具有此默认值,则说明调用者未指定参数。如果参数具有非默认值,则说明它来自调用方。

三国纷争

您可以为可选参数指定一个默认值,该值将不会传递给函数,并使用is运算符进行检查:class _NO_DEFAULT:&nbsp; &nbsp; def __repr__(self):return "<no default>"_NO_DEFAULT = _NO_DEFAULT()def func(optional= _NO_DEFAULT):&nbsp; &nbsp; if optional is _NO_DEFAULT:&nbsp; &nbsp; &nbsp; &nbsp; print("the optional argument was not passed")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("the optional argument was:",optional)那么只要您不这样做func(_NO_DEFAULT),就可以准确地检测出是否传递了参数,并且与接受的答案不同,您不必担心**表示法的副作用:# these two work the same as using **func()func(optional=1)# the optional argument can be positional or keyword unlike using **func(1)&nbsp;#this correctly raises an error where as it would need to be explicitly checked when using **func(invalid_arg=7)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python