Python (2.7.6) function objects and closures, python2.7.6
In Python, everything is an object. A function is also an object. It can be assigned to other variables or passed as a parameter.
Lambda expressions can create function objects. in Python, the function body of a lambda expression can only have one unique statement, that is, the return value expression statement.
cube = lambda x : x ** 3print type(cube) # <type 'function'>print cube(5)
Built-in functions with function objects as parameters: map, filter, and reduce.
The map function receives a function object, acts on each element in the list in turn, and places the returned result in the new list:
>>> map(lambda x: x ** 2, xrange(5))[0, 1, 4, 9, 16]
The filter function receives a function object, acting on each element in the list in turn, and placing the elements whose return result is True in the new list:
>>> filter(lambda s : len(s) > 3, 'Beautiful is better than ugly'.split(' '))['Beautiful', 'better', 'than', 'ugly']
The reduce function receives a function object. This function must receive two parameters. The function first acts on the first two elements of the List, and uses the result and the next element as the parameters for the next call. This applies progressively to the entire list:
>>> reduce(lambda a,b: a*b, [1, 2, 3, 4, 5]) # ((((1*2)*3)*4)*5)120
In Python, if a local variable defined in an external function is referenced in an internal function, the internal function is considered as a closure, the local variables referenced by internal functions are called free variables.
def fall(v0): g = 9.8 return lambda t: v0 * t + 0.5 * g * t ** 2freefall = fall(v0 = 0)print freefall(5)
The _ closure _ attribute of the internal function saves the value of the free variable:
print freefall.__closure__[0].cell_contents # 9.8