【发布时间】:2018-04-11 17:12:35
【问题描述】:
我目前正在使用 python 中的多个订单函数,作为练习,我想尝试使用函数装饰器。在这个例子中,我有一个简单的计数器,并希望使用 datetime 来估计计算机计算到给定代码的某个值所需的时间:
from datetime import datetime
def elapsedTime(f):
time1=datetime.now()
def runFunc():
return f()
time2=datetime.now()
return time2-time1
@elapsedTime
def count(n):
out=0
for i in range(n):
out += 1
return out
out, deltaT= count(50000)
print("count(50000) returns:", out)
print("elapsed time (sec): ", deltaT.total_seconds())
print("type of deltaT: ", type(deltaT))
我期望的输出是:
count(50000) returns: 50000
elapsed time (sec): (calculated value)
type of deltaT: <class 'datetime.timedelta'>
但是,每当我尝试运行此代码时,我都会在第 17 行(我在此处调用 count(50000))收到错误消息:
TypeError: 'datetime.timedelta' object is not callable
我对此有点迷茫,希望有人能指出错误发生的位置。
【问题讨论】:
标签: python python-3.x datetime typeerror python-decorators