装饰器-wraps

Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,Python的functools包中提供了一个叫wraps的decorator来消除这样的副作用。写一个decorator的时候,最好在实现之前加上functools的wrap,它能保留原有函数的名称和docstring。
不加wraps:

#coding=utf-8
# -*- coding=utf-8 -*- 
from functools import wraps   
def my_decorator(func):
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Calling decorated function...')
        return func(*args, **kwargs)
    return wrapper  
 
@my_decorator 
def example():
    """Docstring""" 
    print('Called example function')
print(example.__name__, example.__doc__)


执行结果

('wrapper', 'decorator')
[Finished in 0.2s]

 

加wraps:

#coding=utf-8
# -*- coding=utf-8 -*- 
from functools import wraps   
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        '''decorator'''
        print('Calling decorated function...')
        return func(*args, **kwargs)
    return wrapper  
 
@my_decorator 
def example():
    """Docstring""" 
    print('Called example function')
print(example.__name__, example.__doc__)

执行结果:

('example', 'Docstring')
[Finished in 0.5s]

 

 

原文链接:

https://blog.csdn.net/hqzxsc2006/article/details/50337865
posted @ 2019-08-31 16:44  刘华强等待瓜熟的日子  阅读(987)  评论(0编辑  收藏  举报