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

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

问题描述

我有一个接受多个参数的 Python 函数.在某些情况下,其中一些参数可以省略.

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

参数 dh 是字符串,每个字符串都有不同的含义.重要的是我可以选择以任意组合传递哪些可选参数.例如,(a, b, C, d, e),或 (a, b, C, g, h),或 (a, b、C、d、e、f 或所有这些(这些是我的选择).

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).

如果我可以重载函数就好了 - 但我读到 Python 不支持重载.我尝试在列表中插入一些必需的 int 参数 - 并出现参数不匹配错误.

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?

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

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]

推荐答案

试着这样称呼它: obj.some_function( '1', 2, '3', g="foo", h="bar").在必需的位置参数之后,您可以按名称指定特定的可选参数.

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天全站免登陆