如何用可选参数创建Python函数? [英] How do I create a Python function with optional arguments?

查看:109
本文介绍了如何用可选参数创建Python函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python函数需要几个参数。

  def some_function(self,a,b,c,d = None, e = None,f = None,g = None,h = None):
#code

参数 d h 是各有不同含义的字符串。我可以选择以任意组合传递哪些可选参数,这一点很重要。例如,(a,b,C,d,e)(a,b,C,g,h)(a,b,C,d,e,f ,或全部(这些是我的选择)。

如果我可以重载函数会很好 - 但是我读到Python不支持重载。我试图在列表中插入一些必需的int参数 - 并且得到一个参数不匹配错误。 / p>

现在我发送空字符串代替前几个缺少的参数作为占位符,我希望能够使用实际值调用函数。



有没有办法做到这一点?我可以传递一个列表而不是参数列表吗?



现在原型使用ctypes看起来像这样:

  _fdll.some_function.argtypes = [c_void_p,c_char_p,c_int,c_char_p,c_char_p,c_char_p,c_char_p ,c_char_p] 


解决方案

尝试调用它: obj.some_function('1',2, 3’ ,G = foo 的,H = 栏)。在所需的位置参数之后,您可以按名称指定特定的可选参数。


I have a Python function which takes several arguments. Some of these arguments could be omitted in some scenarios.

def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None):
    #code

The arguments d through h are strings which each have different meanings. It is important that I can choose which optional parameters to pass in any combination. For example, (a, b, C, d, e), or (a, b, C, g, h), or (a, b, C, d, e, f, or all of them (these are my choices).

It would be great if I could overload the function - but I read that Python does not support overloading. I tried to insert some of the required int arguments in the list - and got an argument mismatch error.

Right now I am sending empty strings in place of the first few missing arguments as placeholders. I would like to be able to call a function just using actual values.

Is there any way to do this? Could I pass a list instead of the argument list?

Right now the prototype using ctypes looks something like:

_fdll.some_function.argtypes = [c_void_p, c_char_p, c_int, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p]

解决方案

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

这篇关于如何用可选参数创建Python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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