Python的闭包以及迭代器

一,闭包

什么是闭包呢?闭包就是内层函数,对外层函数(非外层)的变量的引用,叫做闭包

1 def mz():
2     name = 'YJ'
3     def xue():
4         print(name)     #闭包
5     xue()
6 mz()
7 结果:YJ

我们可以使用__closure__来检查函数是否为闭包,使用函数名__closure__返回内存地址就是闭包,返回None就不是闭包

1 def mz():
2     name = 'YJ'
3     def xue():
4         print(name)     #闭包
5     xue()
6     print(xue.__closure__ )     #(<cell at 0x0000017198AB48B8: str object at 0x00000171989C76C0>,)
7 mz()

问题那么来了,如何在函数外边调用内部函数呢?

1 def mz():
2     name = 'YJ'
3     #内部函数
4     def xue():
5         print(name)
6     return xue
7 mingzhi = mz()  #访问外部函数,获取到内部函数的函数地址
8 mingzhi()   访问内部函数

那么如果多层嵌套呢?很简单,只需要一层一层的往外层返回就行了

1 def xue():
2     def xue1():
3         def xue2():
4             print('坚持')
5         return xue2
6     return xue1
7 xue()()()
8 结果:坚持
由它我们可以引出闭包的好处. 由于我们在外界可以访问内部函数. 那这个时候内部函数访问的时间和时机就不一定了, 因为在外部, 我可以选择在任意的时间去访问内部函数,
这个时候. 想一想. 我们之前说过, 如果一个函数执行完毕. 则这个函数中的变量以及局部命名空间中的内容都将会被销毁. 在闭包中. 如果变量被销毁了,
那内部函数将不能正常执行,所以, python规定如果你在内部函数中访问了外层函数中的变量,那么这个变量将不会消亡将会常驻在内存中,也就是说
使用闭包, 可以保证外层函数中的变量在内存中常驻,供后面的程序使用
闭包的好处:

1. 保护你的变量不受外界影响
2. 可以让变量常驻内存
写法:
def outer():
  a = 10
  def inner():
    print(a)
  return inner

三,迭代器

迭代器
使用dir来查看该数据包含了那些方法
用来遍历列表,字符串,元祖....可迭代对象
可迭代对象: Iterable, 里面有__iter__()可以获取迭代器, 没有__next__()
迭代器: Iterator, 里面有__iter__()可以获取迭代器, 还有__next__()

迭代器特点:
1. 只能向前.
2. 惰性机制.
3. 省内存(生成器),只能向下执行

for循环的内部机制.
1. 首先获取到迭代器.
2. 使用while循环获取数据
3. it.__next__()来获取数据
4. 处理异常 try:xxx except StopIteration:

it = xx.__iter__()
while 1:
try:
data = it.__next__()
xxxxxx
except StopIteration:
break

我们之前一直在用可迭代对象进行迭代操作,那么到底什么是可迭代对象目前我们所熟知的可迭代对象都有哪些?

目前所学的可迭代对象有:str, list, tuple, dict, set. 那为什么我们可以称他们为可迭代对象呢?因为他们都遵循了可迭代协议,

什么是可迭代协议,首先我们先看一段错误代码:

1 #可迭代的
2 a = 'Python'
3 for i in a:
4     print(i)
5 #不可迭代的
6 b = 123
7 for el in b:
8     print(el)

 注意看报错的信息中有这样的一句话TypeError: 'int' object is not iterable翻译过来就是整数数据类型对象是不可迭代的iterable表示可迭代的,那么如何验证你的数据类型是否可迭代的呢?我们可以通过dic函数来查看类中定义好的所有方法

1 a = 'Python'
2 print(dir(a))       #可以打印对象中的⽅方法和函数
3 print(dir(str))     # 也可以打印类中声明的⽅方法和函数

在打印结果中. 寻找__iter__ 如果能找到,那么这个类的对象就是一个可迭代对象了

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

字符串中可以找到__iter__这些也是可以找到的list, tuple, dict, set

可以进行for循环的东西都有__iter__函数,包括range也有,可以自己试一下

那么我们认为这个对象遵守了可迭代协议就可以获取到相应的迭代器,这里的__iter__是帮助我们获取到对象的迭代器. 我们使用迭代器中的__next__()来获取到一个迭代器中的元素. 那么我们之前讲的for的工作原理到底是什么? 看如下代码:

 for循环机制

 1 for i in [1,2,3]: 
  2 print(i)
 


2019年11月9日
posted @ 2019-11-09 14:04  YJ-TX  阅读(181)  评论(0编辑  收藏  举报