Functions as Objects

Functions are first-class objects in Python. This means that they can be passed around and used just like any other data type. For example, a function can be returned as a result:

def derivative(f):
     def compute(x):
          return (f(x+dx) - f(x))/dx
     return compute

In this example, the compute() function is returned as a result. Within this function, the variable dx is a free variable that will be bound when the function actually executes. The variable f was originally passed to the function derivative() and remains bound to that value in the function compute(). In addition, you can pass a function as an argument to another function:

# Find the zero of a function using Newton’s method # f is a function object representing a mathematical ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.