函数名的使用、闭包、生成器

一、函数名的使用

1、函数名可以当成迭代元素

1 def func1():
2     pass
3 def func2():
4     pass
5 lst=[1,2,func1,func2]

2、函数名可以当成参数传递

1 def func():
2     print("11111")
3 def proxy(fn):
4     fn()
5 proxy(func)

3、函数名可以当成返回值

1 def func()
2     def func1()
3         print("222222")   
4     return func1
5 f=func()                            #函数返回的是func1加上()调用
6 f()

# 注:只要记住函数名可以被当作变量使用

二、闭包

1、含义:可以在函数的内部访问函数外层的局部变量

2、优点:可以保护内部变量不收侵害、可以是变量常驻内存

3、简单的闭包

1 def func():
2     a=10
3     def func1()
4         print(a)
5     return func1
7 f=func
8 f()

三、迭代器

1、用dir()来查看可以执行哪些方法

2、可迭代数据可以使用__iter()__获取迭代器,获取之后可使用__next()__方法

3、迭代器模拟for循环

1 lst=[1,2,3,4]
2 it=lst.__iter__() #获取迭代器
3 def func():
4     try:
5         el=it.__next__()
6         print(el)
7     except StopIteration:
8         break
9 func()

4、判断数据是否可迭代、以及数据是否是迭代器的方法

 1 from collections import Iterable
 2 from collections import Iterator
 3 
 4 lst=[1,2,3]
 5 it=lst.__iter__()
 6 
 7 print(isinstance(lst,Iterable)) #可迭代对象
 8 print(isinstance(lst,Iterator)) #迭代器
 9 
10 print(isinstance(it,Iterable))
11 print(isinstance(it,Iterator))
原文地址:https://www.cnblogs.com/liaopeng123/p/9456260.html