天天看点

Python 高级编程 - @wrap@wrap的作用不使用@wrap使用@wrap

Python @wrap

  • @wrap的作用
  • 不使用@wrap
    • 执行结果
  • 使用@wrap
    • 执行结果

@wrap的作用

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

让我们来看看作用。

不使用@wrap

#coding=utf-8
# -*- coding=utf-8 -*- 

from functools import wraps   
def my_decorator(func):
    def wrapper(*args, **kwargs):
        '''my decorator'''
        print('Calling decorated function...')
        return func(*args, **kwargs)
    return wrapper  
 
@my_decorator 
def example():
    """examples docstring""" 
    print('Called example function')
print(example.__name__, example.__doc__)
           

执行结果

('wrapper', 'my decorator')
           

使用@wrap

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

           

执行结果

('example', 'example docstring')