python 官方WIKI对于iterable与iterator的说明
image.png
1.可迭代(Iterable)对象
from collections.abc import Iterable
class MyIterator(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
obj = MyIterator()
obj.add("aa")
obj.add('bb')
obj.add('cc')
print(isinstance(obj, Iterable))
image.png
obj 不是一个可迭代对象
from collections.abc import Iterable,Iterator
class MyIterator(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
pass
obj = MyIterator()
obj.add("aa")
obj.add('bb')
obj.add('cc')
print(isinstance(obj, Iterable))
print(isinstance(obj, Iterator))
for x in obj:
print(x)
image.png
实现
__iter__
方法后变为可迭代对象 但是obj 不是迭代器对象,并且for循环报错iter()返回错误
from collections.abc import Iterable,Iterator
class MyIterator(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
return iter(self.names)
obj = MyIterator()
obj.add("aa")
obj.add('bb')
obj.add('cc')
print(isinstance(obj, Iterable))
print(isinstance(obj, Iterator))
for x in obj:
print(x)
image.png
支持for迭代但是MyIterator依旧不是迭代器
总结:
实现了__iter__方法,并且__iter__方法返回迭代器对象 的类生成的对象即可迭代对象
2.迭代器(Iterator)
from collections.abc import Iterable,Iterator
class MyIterator(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
return iter(self.names)
obj = MyIterator()
obj.add("aa")
obj.add('bb')
obj.add('cc')
print(isinstance(obj, Iterable))
print(isinstance(obj, Iterator))
for x in obj:
print(x)
next(obj)
image.png
一个迭代器(Iterator)对象不仅可以在for循环中使用,还可以通过内置函数next()函数进行调用。
from collections.abc import Iterable,Iterator
class MyIterator(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
return iter(self.names)
def __next__(self):
return next(iter(self.names))
obj = MyIterator()
obj.add("aa")
obj.add('bb')
obj.add('cc')
print(isinstance(obj, Iterable))
print(isinstance(obj, Iterator))
for x in obj:
print(x)
next(obj)
image.png
总结:
实现了__iter__和__next__方法的类 生成的对象既迭代器
网友评论