Python之functools.wraps()使用介绍

概念

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

不加wraps

代码:

def my_decorator(func):    def wrapper(*args, **kwargs):        '''decorator'''        print('Calling decorated function...')        return func(*args, **kwargs)    return wrapper@my_decoratordef example():    """Docstring"""    print('Called example function')print('name: {}'.format(example.__name__))print('docstring: {}'.format(example.__doc__))

运行结果:

name: wrapperdocstring: decorator

加上wraps

代码:

import functoolsdef my_decorator(func):    @functools.wraps(func)    def wrapper(*args, **kwargs):        '''decorator'''        print('Calling decorated function...')        return func(*args, **kwargs)    return wrapper@my_decoratordef example():    """Docstring"""    print('Called example function')print('name: {}'.format(example.__name__))print('docstring: {}'.format(example.__doc__))

运行结果:

name: exampledocstring: Docstring
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章