python装饰器

来源:互联网 发布:ubuntu下安装jdk9 编辑:程序博客网 时间:2024/04/27 03:07

第一种形式
def decorator(fun):
    logging.warn("before")
    fun()
    logging.warn("after")
    return fun


使用 语法糖

@decorator
def fun():

    print("ok");


上述其实等价于

fun = decorator(fun)


第二种形式,使用类方式

class tracer:
    def __init__(self, func):
        self.calls = 0
        self.func = func


    def __call__(self, *args):
        self.calls += 1
        print('call %s to %s' %(self.calls, self.func.__name__))
        self.func(*args)
@tracer
def spam(a, b, c):
    print a, b, c


spam(19, 29, 30)