function objects and closures in Python

Source: Internet
Author: User

Functions are the first class of objects in Python and can be passed as arguments to other functions, placed in data structures, and returned as functions.

The following example takes another function as input and calls it

1 # foo.py 2 def Callf (func): 3     return func ()

Use the above function:

1 Import Foo 2 def HelloWorld (): 3     return ' Hello,world ' 4 5 print foo.callf (HelloWorld)

>>> ' Hello,world '

2. When a function is treated as data, it will display the information that is relevant to the surrounding environment in which the function is defined.

When the statements that make up a function are packaged together with the execution environment of those statements, the resulting object is called a closure

1 # foo.py 2 x=423def  Callf (func):4     return func ()

When using nested functions, the closure captures the entire environment required for the internal function execution

1 Import Foo 2 def Bar (): 3     X=134     def  HelloWorld ():5         return'   '%x6print  foo.callf (HelloWorld)

>>>hello World. X is 13

function objects and closures in Python

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.