I'm going through a Python OOPs book by Dusty Phillips. I fail to understand a particular program in the book, chapter 7 - Python Object-oriented Shortcuts. The extended version of the code is available here
Although the program comes under the topic Functions are objects too, the provided program also uses a strange code, which i feel, more of imply the opposite (using objects as functions).
I have pointed out the line in the code where i have the doubt. How is that variable callback of TimedEvent used like a function Timer class ? What is going on here in this part.
import datetime
import time
class TimedEvent:
def __init__(self, endtime, callback):
self.endtime = endtime
self.callback = callback
def ready(self):
return self.endtime <= datetime.datetime.now()
class Timer:
def __init__(self):
self.events = []
def call_after(self, delay, callback):
end_time = datetime.datetime.now() + \
datetime.timedelta(seconds=delay)
self.events.append(TimedEvent(end_time, callback))
def run(self):
while True:
ready_events = (e for e in self.events if e.ready())
for event in ready_events:
event.callback(self) ----------------> Doubt
self.events.remove(event)
time.sleep(0.5)
callbackinitialised? You don’t show that part. Is a function assigned to it? Or something else?call_afteris called! Looking at the linked code,call_afteris always invoked with a regular function forcallback. Socallback… just contains a function.