3.2 Functions as first-class objects
In Chapter 2, Introducing Essential Functional Concepts, we looked at ways in which Python functions are first-class objects. In Python, function objects have a number of attributes. The reference manual lists a number of special member names that apply to functions. Since functions are objects with attributes, we can extract the docstring or the name of a function, using special attributes such as __doc__
or __name__
. We can also extract the body of the function through the __code__
attribute. In compiled languages, this introspection can be either impossible or quite complicated.
Additionally, a callable object helps us to create functions. We can consider the callable class definition as a higher-order function. We do need to be judicious in how we use the __init__()
method of a callable object; we should avoid setting stateful class variables. One common application is to use an __init__()
method to create objects that fit the Strategy design...