python装饰器补充之functools包中的wraps

  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kun1280437633/article/details/80315895

Python装饰器decorator)在实现的时候,有一些细节需要被注意。例如,装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)。这样有时候会对程序造成一些不便,例如笔者想对flask框架中的一些函数添加自定义的decorator,添加后由于函数名和函数的doc发生了改变,对测试结果有一些影响。

所以,Python的functools包中提供了一个叫wraps的decorator来消除这样的副作用。写一个decorator的时候,最好在实现之前加上functools的wrap,它能保留原有函数的名称和docstring



# 未加装饰器代码

def test1():
    '''test1...'''
    print('test1')

def test2():
    '''test2...'''
    print('test2')

print (test1.__name__)
print (test1.__doc__)

print (test2.__name__)
print (test2.__doc__)

# 结果:

test1
test1...
test2
test2...

# 加装饰器未加wraps代码:

# coding:utf8
from functools import wraps

def login_required(view_func):
    def wrapper(*args,**kwargs):
        pass
    return wrapper

@login_required
def test1():
    '''test1...'''
    print('test1')

@login_required
def test2():
    '''test2...'''
    print('test2')

print (test1.__name__)
print (test1.__doc__)


print (test2.__name__)
print (test2.__doc__)

#结果:

wrapper
None
wrapper

None

# 加装饰器加wraps代码:

# coding:utf8
from functools import wraps

def login_required(view_func):
    @wraps(view_func)
    def wrapper(*args,**kwargs):
        pass

    return wrapper

@login_required
def test1():
    '''test1...'''
    print('test1')

@login_required
def test2():
    '''test2...'''
    print('test2')

print (test1.__name__)
print (test1.__doc__)

print (test2.__name__)
print (test2.__doc__)

结果:

test1
test1...
test2
test2...



 



猜你喜欢

转载自blog.csdn.net/kun1280437633/article/details/80315895