Python中实现装饰模式的三种方式
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))
切换到不同的实现中,他们的效果是相同的。
相关推荐
FlySky 2020-09-29
chenzulong 2020-08-16
Freeman00 2020-05-01
codercheng 2020-04-09
JakobHu 2020-02-10
xilove0 2020-01-10
Ayiayi00 2019-11-16
88236435 2019-07-01
AdrianAndroid 2016-12-24
QiaoranC 2019-06-29
changcongying 2019-06-28
newtrekWang 2019-06-27
t0ckh 2011-08-16
liuxiaohua 2019-06-27
paopao00 2019-06-27
homesmile 2015-03-30
zhangbeizhen 2019-06-27
Elixir 2019-06-21