本文實例講述了Python使用修飾器執行函數的參數檢查功能。分享給大家供大家參考,具體如下:
參數檢查:1. 參數的個數;2. 參數的類型;3. 返回值的類型。
考慮如下的函數:
import htmldef make_tagged(text, tag): return '<{0}>{1}</{0}>'.format(tag, html.escape(text))顯然我們希望傳遞進來兩個參數,且參數類型/返回值類型均為str,再考慮如下的函數:
def repeat(what, count, separator) : return ((what + separator)*count)[:-len(separator)]
顯然我們希望傳遞進來三個參數,分別為str,int,str類型,可對返回值不做要求。
那么我們該如何實現對上述參數要求,進行參數檢查呢?
import functoolsdef statically_typed(*types, return_type=None): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if len(args) > len(types): raise ValueError('too many arguments') elif len(args) < len(types): raise ValueError('too few arguments') for i, (type_, arg) in enumerate(zip(types, args)): if not isinstance(type_, arg): raise ValueError('argument {} must be of type {}'.format(i, type_.__name__)) result = func(*args, **kwargs) if return_type is not None and not isinstance(result, return_type): raise ValueError('return value must be of type {}'.format(return_type.__name__)) return wrapper return decorator這樣,我們便可以使用修飾器模板執行參數檢查了:
@statically_typed(str, str, return_type=str)def make_tagged(text, tag): return '<{0}>{1}</{0}>'.format(tag, html.escape(text))@statically_typed(str, int, str)def repeat(what, count, separator): return ((what + separator)*count)[:-len(separator)]注:從靜態類型語言(C/C++、Java)轉入 Python 的開發者可能比較喜歡用修飾器對函數的參數及返回值執行靜態類型檢查,但這樣做會增加 Python 程序在運行期的開銷,而編譯型語言則沒有這種運行期開銷(Python 是解釋型語言)。
更多關于Python相關內容可查看本站專題:《Python函數使用技巧總結》、《Python數據結構與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答