![](/img/trans.png)
[英]What exception to raise if wrong number of arguments passed in to **kwargs?
[英]Raise a specific error message if the number of arguments passed in a function call is not the same as the number of arguments in its definition?
假设我在Python中只有一个定义的函数
def foo(x, y, z):
return x + y + z
然后,我这样调用此函数:
foo(20, 30)
当然,默认情况下,Python会引发有关参数数量的错误。 但是有没有办法自定义此错误消息?
可能还有另一种更好的方法,但是一种解决方案是让您的函数接受任意数量的参数,然后检查调用函数时传递的参数数量:
def foo(*args):
if len(args) != 3:
raise TypeError("Custom error!")
return sum(args)
foo(1, 2, 3)
# 6
foo(1, 2)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "<stdin>", line 3, in foo
# TypeError: Custom error!
您可以将参数的默认值设置为“无”或其他可能是无效输入的值:
def foo(x=None, y=None, z=None):
for param_value in (x, y, z):
if param_value is None:
raise ValueError("Need to provide foo, bar and baz values")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.