不用@的方式实现装饰器,用原始语句应该怎样实现,是不是与不带参数的不同?
比如作业里面的那道题 如果用视频里说的原始语句实现装饰器 应该是 factorial=performance(factorial) 这样是不能实现的
所以正确的应该怎么写? 谢谢大家解答。
比如作业里面的那道题 如果用视频里说的原始语句实现装饰器 应该是 factorial=performance(factorial) 这样是不能实现的
所以正确的应该怎么写? 谢谢大家解答。
2018-08-08
import time
def performance(unit):
def perf_decorator(f):
def wrapper(*args, **kw):
t1 = time.time()
r = f(*args, **kw)
t2 = time.time()
t = (t2 - t1) * 1000
print 'call %s() in %f %s' % (f.__name__, t, unit)
return r
return wrapper
return perf_decorator
perf_decorator=performance('ms')
factorial=perf_decorator(factorial)
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)我认为是这样的,但是运行结果错误,你看看怎么解决,然后告诉我一下,谢谢啦
应该是定义了performance和factorial函数之后,再加一句 factorial=performance(factorial)
如:
import time
def performance(f):
def fn(*args):
t1 = time.time()
r = f(*args)
t2 = time.time()
print 'call %s() in %fs' % (f.__name__, (t2 - t1))
return r
return fn
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
factorial = performance(factorial)
print(factorial(10))
举报