错误捕获 - 调用函数时请求的参数数量不正确

Error catching - incorrect number of arguments requested when calling the function

我遇到一个有趣的问题:

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

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 是无效的:(

使用*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)}")

我认为最好的办法是使用装饰器,您的异常发生在函数调用时,而不是在您尝试打印时。这就是为什么你不排除错误,因为你的错误发生在你的 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/