Python中实现装饰模式的三种方式

peterlee 2017-07-06

Python中实现装饰模式的三种方式

功能目标

编写一个可以打印被装饰函数名称、执行时间、内存地址得装饰器

前置依赖包

import time
import functools
from decorator import decorator

基于普通的函数嵌套

> def log1(fn):
     def _wrapper(*args, **kwargs):
        start = time.clock()
        result = fn(*args, **kwargs)
        print("%s is invoked with time consumed: %s seconds at address %s" % (fn.__name__, str(time.time() - start), id(fn)))
        return result
    return _wrapper

基于@decorator

@decorator
def log(f, *args, **kwargs):
    start = time.time()
    result = f(*args, **kwargs)
    print("%s is invoked with time consumed: %s at address %s" % (f.__name__, str(time.time() - start), id(f)))

    return result

使用@functools

def log2(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        start = time.clock()
        result = f(*args, **kwargs)
        print("%s is invoked with time consumed: %s seconds at address %s" % (f.__name__, str(time.time() - start), id(f)))
        return result
    return wrapper

测试

@log2
def f11(x, y):
    return x**y

result = f11(2,3)
print("result:" + str(result))

切换到不同的实现中,他们的效果是相同的。

相关推荐