O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required