Using Classes Instead of Closures

Take a look at a scenario in which the use of classes is preferred over the use of closures in order to allow for more complex initialization requirements.

Callable class instance

While we are looking at classes, it is worth mentioning that you can create classes that can be “called” like functions. All we need to do is to define a method, __call__, in the class. This is useful to know but probably not something you will use often.

__call__ is one of the special methods that Python provides to allow user-defined objects to support Python operators. All the methods have two underscores before and after their names to distinguish them from normal methods. For that reason, they are sometimes called “dunder” methods (double underscore), or, alternatively, magic methods. The __call__ method supports function calling.

The example code is shown below. We modify the class called Format, to include a __call__ method instead of the previous format method. Now we create an object, format3, as before. But, this time, in order to invoke it, we just need to use the same syntax as we would use to call a function.

Get hands-on with 1200+ tech skills courses.