问题
I try to run a class method in Python 3 every n seconds.
I thought that Threading would be a good approach. The question (Run certain code every n seconds) shows how to do that without objects.
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)
I get this error.
Can you help me doing it right?
回答1:
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()
来源:https://stackoverflow.com/questions/26940591/run-a-class-method-every-n-seconds