October 2018
Beginner to intermediate
466 pages
12h 2m
English
Just as functions are objects that can have attributes set on them, it is possible to create an object that can be called as though it were a function.
Any object can be made callable by simply giving it a __call__ method that accepts the required arguments. Let's make our Repeater class, from the timer example, a little easier to use by making it a callable, as follows:
class Repeater:
def __init__(self):
self.count = 0
def __call__(self, timer):
format_time(f"repeat {self.count}")
self.count += 1
timer.call_after(5, self)
timer = Timer()
timer.call_after(5, Repeater())
format_time("{now}: Starting")
timer.run()
This example isn't much different from the earlier class; all we did was change the name of the repeater function ...