我尝试每隔n秒在Python 3中运行一个类方法。
我认为Threading将是一个很好的方法。问题(Run certain code every n seconds)显示了如何在没有对象的情况下做到这一点。
我试图将此代码“转移”到OOP,如下所示:
class Test:
import threading
def printit():
print("hello world")
threading.Timer(5.0, self.printit).start()
test = Test()
test.printit()
>> TypeError: printit() takes no arguments (1 given)
我收到这个错误。
你能帮我做对吗?
将参数self添加到printit方法中,它适用于我。此外,import语句应位于文件的顶部,而不是在类定义中。
import threading
class Test:
def printit(self):
print("hello world")
threading.Timer(5.0, self.printit).start()
test = Test()
test.printit()