Main content:
1. Use of function names
2. Closed Package
3. iterators
Application of Function name
The function name is a variable, but he is a special variable, with parentheses to match the variables of the executable function.
1. memory address of Function name
def func (): Print (' hehe ') Print (func) # Results # <function func at 0x000000000215d7b8>
2. Function name can be assigned to other variables
def func (): Print (' hehe ') Print = Funca ()
3, function name can be used as the element of the container class
deffunc1 ():Print("I was 1 .") defFunc2 ():Print("I was 2 .") deffunc3 ():Print("I was 3 .") LST=[Func1, Func2, func3] forElinchLst:el ()
4. Function name can be used as parameter of function
def func (): print ( " Did you eat " ) def Func2 (FN): print ( ' I am func2 " ) FN () print ( " I'm Func2 " ) Func2 (func)
5, function name can be the return value of a function
def Func_1 (): print ( " here is the function 1 " ) def func_ 2 (): print ( ' Here is the function 2 " ) print (" here is the function 1 Span style= "COLOR: #800000" > " ) return FUNC_2FN = Func_1 () FN ()
Second, closed package
A closure is a reference to an inner layer function (non-global) variable of the outer layer function. You can use __CLOSURE__ to detect whether a function is closed, return a cell is a closure, and return none is not a closure.
def func1 (): ' Alex ' def Func2 (): Print (name) Func2 () print(func2. __closure__) func1 ()
Call an intrinsic function outside the function:
If you have multiple layers of nesting, you need to go back one layer at a level:
Benefits of closures:
1. Protect your variables from external influences
2, can let the variable resident memory
Three, iterators
To see whether an object can iterate methods:
Wild path:
L = [1,2,3,4= L.__iter__()print('__iter__'in dir (it))print('__next__' in Dir (it))
Official method:
Use the while loop + iterator to simulate A for loop:
LST = ['haha','hehe','La la','Ho Ho']it= LST.__iter__() while1: Try: El= it.__next__() Print(EL)exceptstopiteration: Break
Summarize:
Iterable: An iterative object containing the __iter__ () function inside
Iterator: Iterator with internal __iter__ () containing __next__ ().
Features of iterators:
1. Save Memory
2. Inertia mechanism
3, can not be repeated, only down execution
2018.8.10 iterators in Python