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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
基于@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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
使用@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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
测试
@log2
def f11(x, y):
return x**y
result = f11(2,3)
print("result:" + str(result))
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
切换到不同的实现中,他们的效果是相同的。
http://www.woaipu.com/shops/zuzhuan/61406
http://www.znds.com/tv-967956-1-1.html
http://www.znds.com/tv-967958-1-1.html