Skip to main content
 首页 » 编程设计

python之如何将当前对象引用(自身)传递给 timeit 模块的 Timer 类

2025年05月04日14birdshome

我正在尝试将当前对象引用(即 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”错误。如果我们尝试通过 ma​​in 访问该对象,它就可以工作(下一条注释行工作得很好)。有人可以请问为什么这种行为如此。
提前致谢。

请您参考如下方法:

不要使用字符串,Timer 也接受可调用对象,所以直接传递一个绑定(bind)到 self 的引用,即

T = Timer(self.my_func) 

(只是引用,不要调用它)。

如果您需要更复杂的设置,再次将其包装在函数或方法中并传递该方法。