【问题标题】:Python - Wrong number of arguments exception?Python - 错误数量的参数异常?
【发布时间】:2018-08-24 20:29:42
【问题描述】:

所以我有一个类似的功能:

def my_code(arg1, *args):
    ....

我希望这个函数只能接受 2 个或 3 个参数(这意味着 *args 只能是 1 个或 2 个参数)。如果参数数量错误,如何抛出错误消息?如果我使用 try/exception,是否有特定的异常类型?

【问题讨论】:

  • 你应该提出TypeError
  • 如果你只想取2或3个参数,听起来最好将函数定义为def func(arg1, arg2, arg3=None),或者写两个函数。
  • 自己解决这个问题的方法是编写一个接受两个参数的函数,用一个或四个参数调用它,然后看看会引发什么异常。您想使用相似的文本引发相同的异常(但可能提供更多信息——确切的文本无关紧要。只是异常类型)。

标签: python python-3.x exception error-handling try-catch


【解决方案1】:

您可以使用len 获取args 的长度,就像对任何元组一样。

def my_code(arg1, *args):
    if not 0 < len(args) < 3:
        raise TypeError('my_code() takes either 2 or 3 arguments ({} given)'
                        .format(len(args) + 1))

my_code(1) # TypeError: my_code() takes either 2 or 3 arguments (1 given)
my_code(1, 2) # pass
my_code(1, 2, 3) # pass
my_code(1, 2, 3, 4) # TypeError: my_code() takes either 2 or 3 arguments (4 given)

【讨论】:

  • 为了使错误与内置参数检查一致,我建议raise TypeError('my_code() takes either 2 or 3 arguments (%d given)' % (len(args) + 1))
  • 如果你真的想变得花哨,你可以import sys 并使用sys._getframe().f_code.co_name 以编程方式提取函数名称......尽管根据项目的大小,这可能有点矫枉过正。
  • 我认为您实际上可以使用inspect 做得更简单:inspect.stack()[0][3]
【解决方案2】:

你的测试是:

if len(args) not in (1,2):

当然还有其他表达方式。

至于异常,如果你调用一个带有错误数量参数的内置函数,你会得到一个TypeError。如果您的应用程序不能证明创建自己的 Exception 子类是合理的,那么这可能就是要走的路。

【讨论】:

    【解决方案3】:

    def my_code(*args): if len(args)>2: raise TypeError else: #code for your function pass

    基本上 *args 是一个元组,如果你想要最大数量的参数,你可以引发 TypeError

    【讨论】:

    • 你不需要else
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2023-04-03
    • 2016-07-03
    • 2016-05-04
    • 2019-09-02
    • 1970-01-01
    相关资源
    最近更新 更多