为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

隔江千里 2019-10-16 14:42:34
Python中有没有一种方法可以在调用函数时将可选参数传递给函数,并且函数定义中的代码基于“仅当传递了可选参数时”
查看完整描述

3 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

在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某个调用者将永远不会使用的默认参数值。如果参数具有此默认值,则说明调用者未指定参数。如果参数具有非默认值,则说明它来自调用方。


查看完整回答
反对 回复 2019-10-16
?
三国纷争

TA贡献1804条经验 获得超7个赞

您可以为可选参数指定一个默认值,该值将不会传递给函数,并使用is运算符进行检查:


class _NO_DEFAULT:

    def __repr__(self):return "<no default>"

_NO_DEFAULT = _NO_DEFAULT()


def func(optional= _NO_DEFAULT):

    if optional is _NO_DEFAULT:

        print("the optional argument was not passed")

    else:

        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) 


#this correctly raises an error where as it would need to be explicitly checked when using **

func(invalid_arg=7)


查看完整回答
反对 回复 2019-10-16
  • 3 回答
  • 0 关注
  • 488 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信