【发布时间】:2010-09-13 06:32:25
【问题描述】:
我正在尝试将当前对象引用(即 self)传递给 timeit 模块的 Timer 类,但不知何故我不知道该怎么做。我试图在 timeit 文档中找到它,但我找不到它。我已将我的代码附在这个问题上。
from timeit import Timer
import time
import math
class PollingDemo(Thread):
def __init__(self):
pass
def looper(self):
while 1:
try:
T = Timer("self.my_func()")
#T = Timer("polling.my_func()", "from __main__ import polling")
time_elapsed = T.timeit(1)
if math.ceil(time_elapsed) == 1:
print "Process is sleeped for 1 sec"
time.sleep(1)
except KeyboardInterrupt:
return
def my_func(self):
pass
if __name__ == '__main__':
polling = PollingDemo()
polling.looper()
在此示例中,我尝试通过 Timer 类 timeit() 方法调用 PollingDemo 类的 my_func() 方法,但我收到“NameError: global name 'self' is not defined”错误。如果我们尝试通过 main 访问该对象,它就可以工作(下一个注释行可以正常工作)。有人可以请为什么这种行为会这样。
提前致谢。
【问题讨论】:
标签: python