2016-11-20 134 views
1

我知道我可以創建一個名爲參數化Python函數如命名參數沒有默認值?

def t(a=None, b=None): 
    return a+b 

然後,我可以用

t(b=2, a=5) 

叫然而,如果兩個a & b是不可選的,那麼我就需要檢查運行時的函數,例如

def t(a=None, b=None): 
    if a is not None and b is not None: 
     return a+b 
    else: 
     raise Exception('Missing a or b') 

是否可以檢查編譯時間並儘快失敗?

例如

t(a=3) # raise error 
+3

爲什麼你一直在使用默認值呢? –

回答

1

However, if both a & b are not optional, then I need to check in the function in runtime, e.g.

不,你不會。只是不提供默認值:

def t(a, b): 
    return a + b 

試圖調用它沒有正確的數量參數:

t() 

將導致一個錯誤:

TypeError: t() takes exactly 2 arguments (0 given) 

或者,試圖把它用錯誤地命名參數:

t(c=4) 

也會導致錯誤:

TypeError: t() got an unexpected keyword argument 'c' 
5

如果參數不是可選的,請不要使用默認值。

您仍然可以在調用中將這些參數用作命名參數; 在Python函數中的所有參數被命名爲:

def t(a, b): 
    return a+b 

t(a=3, b=4) 

注意,傳遞的參數錯誤計數始終是一個運行檢查,而不是一個編譯時檢查。作爲一種動態語言,在編譯時不可能知道調用它時實際的對象t