如何在python函数中强制使用一个关键字
我正在实现一个包含三个关键字的函数。每个关键字的默认值为如何在python函数中强制使用一个关键字,python,function,methods,arguments,keyword,Python,Function,Methods,Arguments,Keyword,我正在实现一个包含三个关键字的函数。每个关键字的默认值为None,但我需要强制用户至少传递一个关键字。我之所以要使用关键字,是因为关键字名称a、b和c是描述性的,可以帮助用户了解需要传递给方法的内容。我如何完成我的任务 def method(a=None, b=None, c=None): if a!=None: func_a(a) elif b!=None: func_b(b) elif c!=None: func_c(
None
,但我需要强制用户至少传递一个关键字。我之所以要使用关键字,是因为关键字名称a、b
和c
是描述性的,可以帮助用户了解需要传递给方法的内容。我如何完成我的任务
def method(a=None, b=None, c=None):
if a!=None:
func_a(a)
elif b!=None:
func_b(b)
elif c!=None:
func_c(c)
else:
raise MyError('Don\'t be silly, user - please!')
在上面的示例中,当然假设a、b
和c
具有不同的属性。显而易见的解决办法是:
def method(x):
if is_instance(x, A):
func_a(x)
elif is_instance(x, B):
func_b(x)
[...]
但问题是,正如我所说,我想使用关键字名称a、b
和c
,以帮助用户理解他需要传递给方法的内容
有没有一种更符合python的方法来实现这个结果?您可以使用它来提前引发错误:
def foo(a=None, b=None, c=None):
if all(x is None for x in (a, b, c)):
raise ValueError('You need to set at least *one* of a, b, or c')
if a is not None:
func_a(a)
# etc.
尝试使用此表达式计算是否至少传递了一个参数
if not (a or b or c):
raise MyError
您可以使用decorator,模拟契约编程范式
def check_params(func):
def wrapper(*args, **kwargs):
a = kwargs.get('a', None)
b = kwargs.get('b', None)
c = kwargs.get('c', None)
if (a == b == c == None):
raise Exception("Set one of a, b or c is mandatory.")
else:
return func(*args, **kwargs)
return wrapper
@check_params
def foo(a=None, b=None, c=None):
print("Ok")
foo(a=4) # This will print ok.
foo() # This will rise an exception.
请注意,诸如method(b=“something”,a=“otherthing”)
之类的调用将返回func\u a(a)
,而不是用户可能期望的func\u b(b)
。事实上,最好确保关键字不是None
(参见示例),对于这一点,用户直接调用相应的方法可能更有意义(尽管您可能希望从\u a
等处调用它们method\u)。这是哪个Python版本?在Python3.4中,您可以使用单分派通用函数来完成此任务:@SimeonVisser感谢您提供的链接,这非常有趣!不幸的是,我一直使用python 2.7。我想我想要超载,就是这样@西蒙维瑟也感谢你的链接。每天你都会学到一些新的东西。如果a
,b
或c
可以假定一个错误但有效的值(例如0
或任何空容器),这将失败。有趣的方法,尽管你可以使用