【问题标题】:Error catching - incorrect number of arguments requested when calling the function错误捕获 - 调用函数时请求的参数数量不正确
【发布时间】:2022-01-25 17:23:36
【问题描述】:

我遇到了一个有趣的问题:

我们以这样一个函数为例:

def SumNumbers(a,b,c,d,e,f):
  try:
    print("Marta: ",
        a,"+",b,'+',c,'+',d,'+',e,'+',f,
        '=',
        a + b + c + d + e + f)
  except TypeError:
      print("Enter the values for the 6 parameters of the program")

在这种情况下我们如何处理这个错误:

SumNumbers(1,2,3)

在这种情况下:

SumNumbers(1,2,3,4,5,5,6,77,7,8,88,8,8,8,8)

当然,我的意思是在函数体中处理这个错误:)

不幸的是,我拦截 TypeError 的尝试无效:(

【问题讨论】:

    标签: python exception typeerror


    【解决方案1】:

    我认为最好的办法是使用装饰器,您的异常发生在函数调用上,而不是在您尝试打印时发生。这就是为什么你没有排除错误,因为你的错误发生在你的 try 语句之前。这是一个例子:

    def typeErrorException(func):
        def inner(*nums):
            try:
                func(*nums)
            except TypeError:
                print("Invalid input")
        return inner
    
    @typeErrorException
    def SumNumbers(a,b,c,d,e,f):
        print("Marta: ",
            a,"+",b,'+',c,'+',d,'+',e,'+',f,
            '=',
            a + b + c + d + e + f)
    
    
    SumNumbers(1,2,3,4,5,6,7)
    

    在你的函数之前首先调用你的装饰器,用给定的参数尝试你的函数。这意味着您不必显式尝试,除非每次调用该函数。

    更多关于装饰器的信息:https://realpython.com/primer-on-python-decorators/

    【讨论】:

    • 这也很棒,因为SumNumbers 的特定参数可以很容易地进行类型提示和记录(特别是如果使用来自functools 的包装器之一(可能是wraps?)来保持文档字符串)
    【解决方案2】:

    使用*args:

    def SumNumbers(*args):
        if len(args) != 6:
          print("Enter the values for the 6 parameters of the program")
          return
        print(f"Marta: {' + '.join(str(i) for i in args)} = {sum(args)}")
    

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 2018-02-20
      相关资源
      最近更新 更多