Timer class not working as expected. - 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: Timer class not working as expected. (/thread-15819.html) |
Timer class not working as expected. - MuntyScruntfundle - Feb-01-2019 Hi folks. From what I can find on how to compare dates, basically use the < and >, and how to put a class structure together, the following should work. But it doesn't. If I check more than or less than the tripped routine is always returning True. Is this because it's trying to return an object rather than a value??? And why does get dates return ,bound method customer.getsdates blah blah 0x0blahblah? import datetime import time class clstimer: def __init__(self, interval): self.interval=interval self.startdate=datetime.datetime.now() def tripped(): nowdate=datetime.datetime.now() checkdate=self.startdate + datetime.timedelta(seconds=self.interval) if nowdate>checkdate: self.startdate=datetime.datetime.now() return True else: return False def getdates(): nowdate=datetime.datetime.now() checkdate=self.startdate + datetime.timedelta(seconds=self.interval) return str(nowdate), str(checkdate) def main(): tmr=clstimer(5) print(tmr.getdates) while True: if tmr.tripped: print("Tripped") else: print("Nope") time.sleep(1) main()What am I misunderstanding? Many thanks. RE: Timer class not working as expected. - mlieqo - Feb-01-2019 Hello, first of all, you are missing 'self' argument for methods tripped() and getdates(). And second - if you want to execute the method you need to add parentheses like this: print(tmr.getdates())also for tripped method inside your while loop: tmr.tripped()otherwise they are just method references. RE: Timer class not working as expected. - MuntyScruntfundle - Feb-01-2019 But if I put brackets on I get told the defd takes no arguments but I'm supplying 1. That's what I thought, but it just won't have it. RE: Timer class not working as expected. - mlieqo - Feb-01-2019 Yes, as I wrote you also need to add 'self' argument to methods tripped and getdates. def tripped(self): nowdate=datetime.datetime.now() checkdate=self.startdate + datetime.timedelta(seconds=self.interval) if nowdate>checkdate: self.startdate=datetime.datetime.now() return True else: return False def getdates(self): nowdate=datetime.datetime.now() checkdate=self.startdate + datetime.timedelta(seconds=self.interval) return str(nowdate), str(checkdate) RE: Timer class not working as expected. - MuntyScruntfundle - Feb-02-2019 Ahhhhh, crud. Sorry, I had missed that bit in your explanation. Lesson lernt. Many thanks. :o) |