处理可变但数量有限的参数

Handling a variable but bounded number of arguments

这是我使用的代码:

def arithmetic_arranger(eq1 = '', eq2 = '', eq3 = '', eq4 = '', eq5 = '', answers = False):
try:
    print(eq1 + eq2 + eq3 + eq4 + eq5)
except TypeError:
    raise('Does not work')

arithmetic_arranger('hello', 'hola', 'konnichiwa', 'bonjour', 'hi', 'hey', 'sup')

我想调用该函数,如果有超过 5 个参数(不包括变量),那么它应该 return(对我而言)'Does not work'。这是我第一次处理异常,我似乎无法弄清楚如何处理来自函数内部的异常。

尝试过:

def arithmetic_arranger(eq1 = '', eq2 = '', eq3 = '', eq4 = '', eq5 = '', answers = False):

try:
print(eq1 + eq2 + eq3 + eq4 + eq5)
except TypeError:
raise('Does not work')
arithmetic_arranger('hello', 'hola', 'konnichiwa', 'bonjour', 'hi', 'hey', 'sup')

得到:

TypeError: arithmetic_arranger() takes from 0 to 6 positional arguments but 7 were given

期待:

Does not work

可以使用*args来处理可变数量的参数,然后在打印语句中使用' '.join()来处理传入少于5个参数的情况:

def arithmetic_arranger(*args):
    if len(args) > 5:
        raise TypeError('Can specify at most five arguments to arithmetic_arranger()')
    print(' '.join(args))

您可以使用 *args 获取参数列表,然后检查长度是否 > 5:

def arithmetic_arranger(*args, answers=False):
    if len(args) > 5:
        return "does not work"
# First is fine
>>> arithmetic_arranger('1', '2', '3', '4', '5')
# Second has 6 args; will not work
>>> arithmetic_arranger('1', '2', '3', '4', '5', '6')
'does not work'
# This is still 6 args; will not work
>>> arithmetic_arranger('1', '2', '3', '4', '5', True)
'does not work'
# This will work because you specified that the last arg is answers; not in *args
>>> arithmetic_arranger('1', '2', '3', '4', '5', answers=True)

请注意 return 的使用,它会向调用者发送一个值。我想你可能把 return 误认为是 raise()?

A good read on *args and **kwargs