加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

迭代器 续

发布时间:2020-12-20 11:00:38 所属栏目:Python 来源:网络整理
导读:在python中,itreable可迭代的——--iter--。即只要含有--iter--方法的都是可以迭代的 如: [].__iter__() 迭代器——__next__。通过next就可以从迭代器中一个一个·的·取值。 ? 只要含有__iter__方法的都是可迭代的——可迭代协议。 迭代器协议 内部含有__

在python中,itreable可迭代的——>--iter--。即只要含有--iter--方法的都是可以迭代的

如:

[].__iter__() 迭代器——>__next__。通过next就可以从迭代器中一个一个·的·取值。

?

只要含有__iter__方法的都是可迭代的——可迭代协议。

迭代器协议

内部含有__iter__和__next__方法的都是迭代器。

from collections import Iterator
from collections import Iterable
class A:
    def __iter__(self):pass
    def __next__(self):pass
a = A()
print(isinstance(a,Iterator))
print(isinstance(a,Iterable))
View Code

?

当注释掉其中一个时

from collections import Iterator
from collections import Iterable
class A:
    #def __iter__(self):pass
    def __next__(self):pass
a = A()
print(isinstance(a,Iterable))
View Code

from collections import Iterator
from collections import Iterable
class A:
    def __iter__(self):pass
    #def __next__(self):pass
a = A()
print(isinstance(a,Iterable))
View Code

因此我们可以得知,只要两个方法都存在时才是一个迭代器。

作用

只有是可迭代对象的时候 才能用for循环

当我们遇到一个新的变量时,不确定能不能for循环的时候,可以用来判断它是否可以迭代。

好处

1,从容器类型中一个一个的取值,会把所有的值都取到。

2,它可以节省内存空间。

?  迭代器并不会在内存中再占有一大块内存,而是随着循环,没错生成一个。即每次next给一个。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读