Beautiful, Idiomatic Python (二)

2017-09-17  本文已影响5人  尼罗河上的小杀手

零、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.

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
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

二、reference

https://coolshell.cn/articles/11265.html

上一篇下一篇

猜你喜欢

热点阅读