Function object
Functions are an integral part of programming languages, but functions as first class objects (first-class object) are a major feature of Python functions.
So what exactly is the first class of objects (First-class object)?
All things are objects in Python, functions are no exception, functions can be assigned to a variable as an object, can be added to a collection object as an element, can be passed as a parameter value to other functions, and can be used as the return value of a function, which is unique to the first class of objects.
1. The function is an object that has three common properties of the object model: ID, type, and value.
#!/usr/bin/env python#-*-coding:utf-8-*-def foo (): print (' from foo ') foo () Print (ID (foo)) print (Type (foo)) print ( Foo
Output
From Foo4406808360<class ' function ' ><function foo at 0x106aa8f28>
2. Functions can be referenced, that is, functions can be assigned to a variable
The function can also be assigned to more variables, the only change is that the function object's reference count is constantly increasing, essentially these variables are ultimately pointing to the same function object.
#!/usr/bin/env python#-*-coding:utf-8-*-def foo (): print (' from foo ') foo () Func=foo #引用, assignment print (foo) print ( Func) func ()
Output
From foo<function foo @ 0x10eed8f28><function foo at 0x10eed8f28>from foo
3. Functions can be passed as parameters
def foo (): print (' from foo ') def Bar (func): print (func) func () bar (foo)
Output
<function foo at 0x1047eff28>from foo
4. Function can be used as a return value
function to accept one or more functions as input or function output (return) value is a function, we call such a function as a higher order function
def foo (): print (' from foo ') def Bar (func): return func f=bar (foo) print (f) f ()
Output
<function foo at 0x107f29f28>from foo
5. Functions can be used as elements of a container type
The Container object (list, dict, set, etc.) can hold any object, including integers, strings, functions can also be stored in the container object
def foo (): print (' from foo ') dic={' func ': Foo}foo () print (dic[' func ']) dic[' func '] ()
Output
From Foo<function foo at 0x10997ef28>from foo
6. Functions can also be nested
Definition of function nesting
Def f1 (): def f2 (): print (' from F2 ') def f3 (): print (' from F3 ') F3 () F2 () F1 ()
Output
From F2from F3
Application
def get (text): def clean (t): #2 return t[1:] new_text = Clean (text) #1 return len (new_ Text) print (Get (' Python '))
Output
5
"The function object of Python3"