1. 概念
1.1. iterable
- 可迭代对象,是可以使用
for 循环遍历的对象 - 实现
__iter__() 方法
- 注意,程序通过判断是否有声明
__iter__() 方法来确认对象是否为可迭代对象,但是得到的对象是否真的能执行for循环并不确定 - string,list,map,set都算是iterable
1.2. iterator
2. 索引迭代
- 对于任意对象
obj ,如果想要使用for i in obj ,就需要满足条件
- obj中有可迭代对象
- 通过
__getitem__(self, index) 来返回可迭代对象中的元素,即通过index来迭代对象
class C():
def __init__(self):
self.list1 = [1, 2, 3, 4]
self.list2 = [5, 6, 7]
def __getitem__(self, item):
return self.list1[item]
c = C()
for i in c:
print(i)
assert not isinstance(c, Iterable)
assert not 5 in c
c1 = iter(c)
print(next(c1))
print(next(c1))
assert isinstance(c1, Iterable)
assert not 5 in c1
3. 可迭代对象iterable
from typing import Iterable
assert isinstance(range(10), Iterable)
class custom_range(object):
def __init__(self, stop, start=0, step=1):
self._cur = start
self._start = start
self._stop = stop
self._step = step
def __iter__(self):
return self
def __next__(self):
if self._cur >= self._stop:
raise StopIteration
current = self._cur
self._cur += self._step
return current
4. 迭代器iterator
assert isinstance(custom_range(10), Iterable)
assert isinstance(iter(custom_range(10)), Iterator)
next(iter(custom_range(10)))
5 生成器
- 生成器(Generator)属于特殊的迭代器(Iterator),当然也就是可迭代对象(Iterable)
- 因此从范围来看,
Generator <Iterator <Iterable - 生成器自动实现了
__iter__() 和__next__()
from typing import Generator, Iterator, Iterable
def generator():
a = [1, 2, 3, 4, 5]
for i in a:
yield i
asset isinstance(generator(), Generator)
asset isinstance(generator(), Iterator)
asset isinstance(generator(), Iterable)
|