有没有办法将可选参数传递给函数? [英] Is there a way to pass optional parameters to a function?

查看:52
本文介绍了有没有办法将可选参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

Python 2 文档,7.6.函数定义为您提供了几种方法来检测调用者是否提供了可选参数.

首先,您可以使用特殊的形参语法*.如果函数定义有一个形式参数,前面有一个 *,那么 Python 会用任何与前面的形式参数(作为元组)不匹配的位置参数填充该参数.如果函数定义有一个以 ** 开头的形式参数,则 Python 会使用任何与前面的形式参数不匹配的关键字参数(作为 dict)填充该参数.该函数的实现可以检查这些参数的内容,以查找您想要的任何可选参数".

例如,这里有一个函数 opt_fun,它接受两个位置参数 x1x2,并查找另一个名为optional"的关键字参数.

<预><代码>>>>def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):...如果(keyword_parameters 中的'可选'):...打印'找到的可选参数,它是',keyword_parameters['可选']... 别的:...打印'没有可选参数,抱歉'...>>>opt_fun(1, 2)没有可选参数,抱歉>>>opt_fun(1,2, optional="yes")找到可选参数,是的>>>opt_fun(1,2, another="yes")没有可选参数,抱歉

其次,您可以提供一些默认参数值,例如调用者永远不会使用的None.如果参数有这个默认值,你就知道调用者没有指定参数.如果参数有一个非默认值,你就知道它来自调用者.

Is there a way in Python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"

解决方案

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "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

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

这篇关于有没有办法将可选参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆