Python function name of the application / closure / iterator /

1. Application of the function name.
  Function name is a variable, but it is a special variable, and can be performed with parentheses variable function.

    1. The memory address of the function name

 

DEF FUNC ():
     Print ( " Oh " )
 Print (FUNC)
 # result: <function func at 0x1101e4ea0>

 

    2. The function name can be assigned to other variables

DEF func ():
     Print ( " Oh " )
 Print (FUNC) 
A = FUNC # to function as a variable to another variable 
A () # function call func ()

    3. The element name can be used as containers of

DEF func1 ():
     Print ( " Oh " )
 DEF func2 ():
     Print ( " Oh " )
 DEF func3 ():
     Print ( " Oh " )
 DEF Func4 ():
     Print ( " Oh " ) 
LST = [func1, func2 , func3]
 for i in LST: 
    i ()

4. The name can be used as parameters of the function

DEF FUNC ():
     Print ( " eat it " )
 DEF func2 (the Fn): 
  
Print ( " I am func2 " )
  the Fn ()
# execute pass over the Fn
  Print ( " I am func2 " ) func2 (FUNC) # put parameters passed to the function func as func2 parameter fn.

The name can be used as the return value of the function

 

DEF func_1 ():
     Print ( " this is a function. 1 " )
     DEF func_2 ():
         Print ( " this is a function 2 " )
     Print ( " this is a function. 1 " )
     return func_2 
Fn = func_1 () # executes the function 1. Function 2 is a function of a return, this time point is above fn 2 function 
fn () # perform the above function returns

 

2. Closure
  What is a closure? Closures is a reference to the inner function, variable external layer function (non-global). Called closures

def outer():
  a = 10 # 很耗时
  def inner():
    print(a)
  return inner
# outer()()
# outer()()
ret = outer()
ret()
ret()
注意:我们可以使用__closure__来检测函数是否是闭包. 使用函数名.__closure__返回cell就是闭包. 返回None就不是闭包
def func1():
    name = "disman"
    def func2():
        print(name) # 闭包
func2()
print(func2.__closure__) # (<cell at 0x10c2e20a8: str object at 0x10c3fc650>,)
func1()

闭包好处:
  1. 保护变量
  2. 可以让一个变量常驻内存
  3. 迭代器
    __iter__() 可迭代对象. 获取迭代器
    __next__() + __iter__() 迭代器

  特点:
    1. 惰性机制
    2. 只能向前
    3. 节省内存
  for循环的内部就是迭代器

lst = [1,2,4]
it = lst.__iter__() # 获取迭代器
while 1:
  try:
      it.__next__() # 从迭代器中获取数据
  except StopIteration:
    break

Iterable: 可迭代的
Iterator: 迭代器

Guess you like

Origin www.cnblogs.com/shagudi/p/10949205.html