首页 > 代码库 > python 装饰器

python 装饰器

最近在学习廖雪峰的python教程,在装饰器的一章中有个思考题:

<!-- lang: python -->

import functools

def log(params):

def decorator():
            @functools.wraps(params)
            def wrapper(*args,**kw):
                    print ‘begin call 1‘
                    params(*args,**kw)
                    print ‘end call 1‘
            return wrapper
    def decorator2(func):
            @functools.wraps(func)
            def wrapper2(*args,**kw):
                    print params,‘begin call 2‘
                    func(*args,**kw)
                    print ‘end call 2‘
            return wrapper2
    if hasattr(params,‘__call__‘):
            return decorator()
    else:
            return decorator2

@log
def now():

print ‘2014‘

@log(‘execute‘)
def now2():

print ‘2015‘

now()
print
now2()

python 装饰器