Functions Are Objects, Too

Learn how Python leverages functions as callable objects for dynamic execution and event-driven programming.

We'll cover the following

Overview

There are numerous situations where we’d like to pass around a small object that is simply called to perform an action. In essence, we’d like an object that is a callable function. This is most frequently done in event-driven programming, such as graphical toolkits or asynchronous servers.

In Python, we don’t need to wrap such methods in a class definition because functions are already objects. We can set attributes on functions (though this isn’t a common activity), and we can pass them around to be called at a later date. They even have a few special properties that can be accessed directly.

Example

Here’s yet another contrived example, sometimes used as an interview question:

Get hands-on with 1400+ tech skills courses.