python中wraps的作用
阿新 • • 發佈:2018-12-12
這裡使用兩段程式碼比較加入wraps裝飾器後,函式列印的結果對比:
程式碼1:不加wraps裝飾器
# coding=utf-8
from functools import wraps
def my_decorator(func):
def wrapper(*args, **kwargs):
'''decorator'''
print('Decorated function...')
return func(*args, **kwargs)
return wrapper
@my_decorator
def test():
"""Testword"""
print('Test function')
print(test.__name__, test.__doc__)
列印結果:
wrapper decorator
[Finished in 0.1s]
程式碼2:加入wrapper函式後
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
'''decorator'''
print ('Decorated function...')
return func(*args, **kwargs)
return wrapper
@my_decorator
def test():
"""Testword"""
print('Test function')
print(test.__name__, test.__doc__)
列印結果:
test Testword
[Finished in 0.1s]
總結:
因為當使用裝飾器裝飾一個函式時,函式本身就已經是一個新的函式;即函式名稱或屬性產生了變化。所以在python的functools
wraps
裝飾函式來確保原函式在使用裝飾器時不改變自身的函式名及應有屬性。所以在裝飾器的編寫中建議加入
wraps
確保被裝飾的函式不會因裝飾器帶來異常情況。