2016-11-13 44 views
0

有沒有什麼辦法通過assert語句來檢查函數參數的存在?python中聲明語句的參數存在

def fractional(x) : 
    assert x==None, "argument missing" <---- is it possible here to check? 
    assert type(x) == int, 'x must be integer' 
    assert x > 0 , ' x must be positive ' 
    output = 1 
    for i in range (1 , int(x)+1) : 
     output = output*i 
    assert output > 0 , 'output must be positive' 
    return output 
y=3 
fractional() <----- argument missing 

回答

1

您不應該明確斷言參數的存在。如果當你調用該函數沒有給出參數,你會得到像一個類型錯誤:

>>> def foo(x): 
...  pass 
... 
>>> foo() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: foo() takes exactly 1 argument (0 given) 
>>> 

如果你想確保參數的其他屬性(你只提到了存在的),你可以測試這些屬性並在不符合時提出例外:

>>> def foo(x): 
... if not isinstance(x, str): 
...  raise ValueError("argument must be a string!") 
... 
>>> foo(42) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 3, in foo 
ValueError: argument must be a string! 
>>>