本文介绍了每n秒运行一次类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试每n秒在Python 3中运行一个类方法.
I try to run a class method in Python 3 every n seconds.
我认为线程化是一种很好的方法.问题(每n秒运行某些代码)说明了如何在不使用此代码的情况下执行此操作.对象.
I thought that Threading would be a good approach. The question (Run certain code every n seconds) shows how to do that without objects.
我试图像这样将代码转移"到OOP:
I tried to "transfer" this code to OOP like this:
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语句应位于文件的顶部,而不是在类定义之内.
Add the argument self into the printit method, and it works for me. Also, import statements should be at the top of the file, not within the class definition.
import threading
class Test:
def printit(self):
print("hello world")
threading.Timer(5.0, self.printit).start()
test = Test()
test.printit()
这篇关于每n秒运行一次类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!