About function objects and closures
Closure (closure) is an important grammatical structure of functional programming. Different languages implement closures in different ways. Python is based on a function object and provides support for the syntactic structure of closures (we have seen Python use objects for some special syntax in special methods and multiple paradigms). Python everything is object, function This syntax structure is also an object. In a function object, we use a function object like a normal object, such as changing the name of a function object, or passing a function object as a parameter.
First, the function object:
1. Functions can be passed as parameters
Example:
#把函数当成参数传递def foo (): #定义foo函数 print (' foo ') def bar (foo): print (foo) #打印foo的内存地址 foo () #调用foo函数bar (foo)
The execution results are:
<function Foo at 0x00000000022eb8c8>foo
2. Function can be assigned value
Example:
def foo (): #定义foo函数 print (' foo ') print (foo) #输出foo的内存地址f =fooprint (f) F () #即foo () Execute the Foo function
The execution results are:
<function foo at 0x00000000003f3e18><function foo at 0x00000000003f3e18>foo
3, the function as the return value
Example:
# function as return value def foo (): #定义foo函数 print (' foo ') def bar (foo): print (foo) return foo# foo as the return value F=bar (foo) print ( f) F ()
The execution results are:
<function foo at 0x0000000001fbb8c8><function foo at 0x0000000001fbb8c8>foo
4, the function as a container type variable (function as a container type variable, can be called at any time on the main axis)
Example:
Def tell_msg (): msg= " Search: Query add: Add Delete: Delete change: Modify Create: Create New " Print (msg)
ii. Closures:(functions defined inside include references to external scopes, excluding references to global scopes)
Determine if it is a closure:
Print (f.__closure__), if the return value is none, it means that it is not a closed packet
Print (f.__closure__[0].cell_contents) returns the value of the closure by index
Print (f.__closure__[1].cell_contents) returns the value of the closure by index
Python Basics-function objects and closures