這是我使用的代碼:
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 個引數(不包括變數),那么它應該回傳(出于我的目的)“不起作用”。這是我第一次處理例外,我似乎無法弄清楚如何從函式內部處理它。
試過:
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
uj5u.com熱心網友回復:
您可以使用*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()?
一個很好的閱讀
*args和**kwargs
uj5u.com熱心網友回復:
可以*args用來處理可變數量的引數,然后' '.join()在 print 陳述句中用來處理傳入的引數少于 5 個的情況:
def arithmetic_arranger(*args):
if len(args) > 5:
raise TypeError('Can specify at most five arguments to arithmetic_arranger()')
print(' '.join(args))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458719.html
上一篇:為什么TextError例外在此代碼中無法正常運行?
下一篇:在頂層正確處理來自異步函式的例外
