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