python decorators
装饰器基础
Decorator 本质
@ 本质是语法糖 - Syntactic Sugar
使用 @decorator 来修饰某个函数 func 时:
1 |
|
其解释器会解释成:
1 | func = decorator(func) |
注意这条语句会被执行
多重装饰器
1 |
|
相当于:
1 | func = decorator_one(decorator_two(func)) |
带参数装饰器
1 |
|
相当于:
1 | func = decorator(arg1,arg2)(func) |
使用 *args、**kwargs
给被装饰函数传递参数
1 | def wrapper(func): |
带参数的装饰器
1 | def log(level): |
等同于
1 | def foo(name='foo'): |
方法装饰器
类方法是一个特殊的函数,它的第一个参数 self 指向类实例
所以我们同样可以装饰类方法
1 | def decorate(func): |
上例相当于固定了 self 参数, 不太灵活
使用 *args, **kwargs
传递给 wrapper 更加通用:
1 | def pecorate(func): |
类装饰器
类实现 __call__
方法后变成可调用对象,故可以用类做装饰器
1 | class EntryExit(object): |
类装饰器
1 |
|
等同于
1 | def func1(): |
装饰器装饰类
1 | register_handles = [] |
1 |
|
1 | Index = route("/index")(Index) |
functools
上述装饰器实现有个问题,就是被装饰函数的属性被改变
Sync From: https://github.com/TheBigFish/blog/issues/7