Python中装饰器的使用

2018-11-12  本文已影响0人  obsession_me

简单装饰器

# simple decorator
def log1(func):
    def wrapper(*args, **kwargs):
        print("logging decorator is running, target is %s" % func.__name__)
        func()
        print("logging decorator is exiting, target is %s" %func.__name__)
    return wrapper


@log1
def test():
    print(time.ctime(time.time()))


if __name__ == "__main__":
    test()

这里输出结果如下:

logging decorator is running, target is test
Mon Nov 12 22:48:46 2018
logging decorator is exiting, target is test

而这里的话,我们去理解到底发生了什么可以用代码去考量,我们使用了装饰器的语法糖,@log1实际上相当于

test = log1(test)

带参数的装饰器

类装饰器

上一篇 下一篇

猜你喜欢

热点阅读