Python的闭包以及迭代器

一,闭包python

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

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

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

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()   访问内部函数

那么若是多层嵌套呢?很简单,只须要一层一层的往外层返回就好了ssh

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 inneride

三,迭代器

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

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

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

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

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

目前所学的可迭代对象有: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日
相关文章
相关标签/搜索