零旨剥、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) 函數(shù)foo 有個(gè)@hello蕴掏, hello就是上面的函數(shù)桥狡。
2) hello函數(shù)中有一個(gè)fn 參數(shù)(fn用來(lái)做回調(diào)的函數(shù))
3) hello函數(shù)中 返回了一個(gè)inner函數(shù)wrapper章贞,這個(gè)wrapper函數(shù)回調(diào)了傳進(jìn)來(lái)的fn,并在回調(diào)前加了自己的函數(shù)體漆枚。
- decorator 去修飾函數(shù)func時(shí)絮缅。
@decorator
def func():
pass
解釋器會(huì)將上面的語(yǔ)句解釋成這樣:
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