夜猫的个人小站

       继续码起来

关于作者

微博北极熊硬糖
北京海淀区

Python四种类型修饰器

标签   Python

#encoding=utf-8
from time import ctime,sleep
import functools
#两者都不带参数
def decorator1(func):  
    print 'execute now  '+func.__name__
    print ctime()
    func()

@decorator1
def test1():
    pass

#装饰函数带有参数,被装饰函数没有
def log(text):  
    def decorator2(func):
        print text
        print 'execute now  '+func.__name__
        print ctime()
        return func()
    return decorator2

@log('NO2')
def test2():
    pass

#装饰函数没有参数,被装饰函数有参数
def decor3(func):
    def wrapper(*args):
        print 'execute now  '+func.__name__
        print ctime()
        return func(*args)
    return wrapper

@decor3
def sum3(*args):
    a=0
    for i in args:
        a=a+i
    return a
b=[1,2,3,4,5]
sum3(*b)

#两者都有参数
def log2(text):
    def deco3(func):
        @functools.wraps(func)
        def wrapper(*args):
            print text
            print 'execute now  '+func.__name__
            print ctime()
            return func(*args)
        return wrapper
    return deco3

@log2('NO4')
def sum4(*args):
    b=0
    for i in args:
        b=b+i
    return b

c=[3,4,5]
sum4(*c)



#显示结果:      
execute now  test1
Thu Nov 12 20:46:39 2015
NO2
execute now  test2
Thu Nov 12 20:46:39 2015
execute now  sum3
Thu Nov 12 20:46:39 2015
NO4
execute now  sum4
Thu Nov 12 20:46:39 2015

最新评论

发表评论
回到顶部