Python Forum
Cannot use function with timer/clock - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Cannot use function with timer/clock (/thread-15568.html)



Cannot use function with timer/clock - theangryprogrammer - Jan-22-2019

I have been working for days now trying to implement a timer, which would take 5 minutes in any other language. I have tried every tutorial in existence and none of them work. I am now on my last nerve and I just do not understand why calling a function in python is so difficult. Below is a snippet of code that demonstrates my problem.

In the example, the function runs fine when called from another function in the class.
Likewise, "self.updateDebugger" is another function (not shown) in the class and calling it seems to be just fine. But if I try to schedule the code using a clock, I get an error stating "AttributeError: 'float' object has no attribute 'updateDebugger'"

class MainWindow(App):

	def clockFunc(self):
		self.updateDebugger("data read @ " + datetime.datetime.now())
		print ("doing stuff")
	
    Clock.schedule_interval(clockFunc, .5)

if __name__ == '__main__':	
	MainWindow().run()
The error "AttributeError: 'float' object has no attribute 'updateDebugger'" I assume is referring to the clock not being able to pass an argument as a a float. Why the clock needs to do such a thing I have no idea. I also dont understand what this has to do with "self.updateDebugger" since this method has nothing to do with the clock. The clock is scheduling the clockFunc() function. If the code runs fine when being called then why can't the clock run the code?


RE: Cannot use function with timer/clock - Larz60+ - Jan-22-2019

In order to use a method from a class outside of the class, you need to intestate a new class, and must pass any required initialization
arguments ('App' for this class).
You also have to return something meaningful from the class method, otherwise it will go out of scope as soon as the method is finished.
arguments passed to class
This code as written has never run, it would fail immediately:
  • Not instantiating class
  • Line 7 doesn't belong in class
  • Have not created instance of class MainWindow
  • Method clockFunc does not take any arguments, yet you are trying to pass .5
  • clockFunc never returns a value
Fix all of above and post new code.
I Strongly recommend reading up on classes, here's a quick and dirty tutorial that you can do in less than 10 minutes: https://www.learnpython.org/en/Classes_and_Objects