Python (2.7.6) function objects and closures, python2.7.6

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.