零、Decorator(@ Syntactic Sugar)
- 装饰器定义
A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
- Hello world
Code:
def hello(fn):
def wrapper():
print("hello, %s" % fn.__name__)
print("hello, %s" % foo.__name__)
fn()
print("goodby, %s" % fn.__name__)
print("goodby, %s" % foo.__name__)
return wrapper
@hello
def foo():
print("i am foo")
foo()
Output:
hello, foo
hello, wrapper
i am foo
goodby, foo
goodby, wrapper
1) 函数foo 有个@hello, hello就是上面的函数。
2) hello函数中有一个fn 参数(fn用来做回调的函数)
3) hello函数中 返回了一个inner函数wrapper,这个wrapper函数回调了传进来的fn,并在回调前加了自己的函数体。
- decorator 去修饰函数func时。
@decorator
def func():
pass
解释器会将上面的语句解释成这样:
func = decorator(func)
一、 Decorator 示例
- 缓存
_cache_db = dict()
def cache(fn):
def wrapper(*args):
result = _cache_db.get(args,None)
if result is None:
result = fn(*args)
_cache_db[args] = result
return result
return wrapper
@cache
def add(a, b):
return a + b
if __name__ == '__main__':
assert add(3, 4) ==7
网友评论