簡體   English   中英

如果在函數調用中傳遞的參數數量與其定義中的參數數量不同,則引發特定的錯誤消息?

[英]Raise a specific error message if the number of arguments passed in a function call is not the same as the number of arguments in its definition?

假設我在Python中只有一個定義的函數

def foo(x, y, z):
    return x + y + z

然后,我這樣調用此函數:

foo(20, 30)

當然,默認情況下,Python會引發有關參數數量的錯誤。 但是有沒有辦法自定義此錯誤消息?

可能還有另一種更好的方法,但是一種解決方案是讓您的函數接受任意數量的參數,然后檢查調用函數時傳遞的參數數量:

def foo(*args):
    if len(args) != 3:
        raise TypeError("Custom error!")
    return sum(args)

foo(1, 2, 3)
# 6
foo(1, 2)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 3, in foo
# TypeError: Custom error!

您可以將參數的默認值設置為“無”或其他可能是無效輸入的值:

def foo(x=None, y=None, z=None):
    for param_value in (x, y, z):
        if param_value is None:
            raise ValueError("Need to provide foo, bar and baz values")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM