python 装饰器

2018-09-01  本文已影响13人  __RY__

装饰器(无参) (多装饰器执行由底向上)

注:此处装饰器的定义只是简单总结,并不准确,只是方便理解


装饰器是高阶函数,但装饰器是对传入函数的功能的装饰(功能增强)

import datetime
import time
def logger(fn):
    def wrapper(*args,**kwargs):
        'this is wrapper function'
        print('args={},kwargs={}'.format(args,kwargs))
        start = datetime.datetime.now()
        ret = fn(*args,**kwargs)
        duration = (datetime.datetime.now() - start).total_seconds()
        print('function {} took {}s'.format(fn.__name__,duration))
        return ret
    return wrapper

@logger
def add(x, y):
    'this is add function'
    return x + y


>>> add(5,5)
> args=(5, 5),kwargs={}
> function add took 0.0s

>>> print(add.__name__)
>>> print(add.__doc__)
> wrapper
> this is wrapper function

上面的例子中我们会发现add函数对象的属性变成了wrapper函数的属性,使用装饰器我们是希望查看被封函数的属性,所以这里我们就需要带参装饰器来解决这个问题


带参装饰器
import datetime
import time

def copy_properties(src):
    def _copy(dest):
        dest.__name__ = src.__name__
        dest.__doc__ = src.__doc__
        return dest
    return _copy

def logger(duration):
    def _logger(fn):
        @copy_properties(fn) 
        # wrapper = copy_properties(fn)(wrapper) => _copy(wrapper) => wrapper
        def wrapper(*args,**kwargs):
            ''' this is  wrapper function '''
            start = datetime.datetime.now()
            ret = fn(*args,**kwargs)
            delta = (datetime.datetime.now() - start).total_seconds()
            print('so slow') if delta > duration else print('so fast')
            return ret

        return wrapper
    return _logger

@logger(6)
def add(x, y):
    ''' this is  add function '''
    time.sleep(3)
    return x + y 

>>> add(3,4)
>>> print(add.__doc__)
> so fast
> this is  add function 

注:这里我们通过copy_properties函数解决了上面属性发生改变的问题。

def logger(duration,func = lambda name,duration:print('{} took {}s'.format(name,duration))):
    def _logger(fn):
        @copy_properties(fn) 
        # wrapper = copy_properties(fn)(wrapper) => _copy(wrapper) => wrapper
        def wrapper(*args,**kwargs):
            ''' this is  wrapper function '''
            start = datetime.datetime.now()
            ret = fn(*args,**kwargs)
            delta = (datetime.datetime.now() - start).total_seconds()
            if delta > duration:
                func(fn.__name__,duration)
            return ret

        return wrapper
    return _logger

在Python functools模块中自带了两个函数可以帮我们更方便的解决使用装饰器时函数属性改变的问题

update_wrapper函数

functools.update_wrapper(wrapper, wrapped, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))

import datetime,time,functools
def logger(duration, func=lambda name,duration: print('{} took {}s'.format(name,duration))):
    def _logger(fn):
        def wrapper(*args,**kwargs):
            start = datetime.datetime.now()
            ret = fn(*args,**kwargs)
            delta = (datetime.datetime.now() - start).total_seconds()
            if delta > duration:
                func(fn.__name__,duration)
            return ret
        return functools.update_wrapper(wrapper,fn)
    return _logger

@logger(5)  # add = logger(5)(add)
def add(x,y):
    time.sleep(2)
    return x+y

print(add(5,6),add.__name__,add.__wrapped__,add.__dict__,sep='\n')


wraps 函数

functools.wraps(wrapped, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',))
import datetime,time,functools
def logger(duration, func=lambda name,duration: print('{} took {}s'.format(name,duration))):
    def _logger(fn):
        @functools.wraps(fn)
        def wrapper(*args,**kwargs):
            start = datetime.datetime.now()
            ret = fn(*args,**kwargs)
            delta = (datetime.datetime.now() - start).total_seconds()
            if delta > duration:
                func(fn.__name__,duration)
            return ret
        return wrapper
    return _logger

@logger(5)  # add = logger(5)(add)
def add(x,y):
    time.sleep(2)
    return x+y

print(add(5,6),add.__name__,add.__wrapped__,add.__dict__,sep='\n')

上一篇下一篇

猜你喜欢

热点阅读