可迭代对象中需要实现__iter__函数,且该函数的返回值为迭代器。
迭代器对象中需要实现__iter__和__next__函数
生成器:一种特殊的迭代器
for循环的过程如下:
for item in some_obj:
# 判断some_obj是否是可以迭代的(isinstance(some_obj,Iterable))
# 使用iter函数获取__iter__的返回值,返回值为迭代器(isinstance(some_obj,Iterator))
# 使用next函数从迭代器中的__next__函数获取值
pass
自定义对象实现可迭代:
class ClassMates(object):
def __init__(self):
self.names = []
def add(self,name):
self.names.append(name)
def __iter__(self):
return ClassIterator(self)
class ClassIterator(object):
def __init__(self, obj):
self.obj = obj
self.cur_idx = 0
def __iter__(self):
pass
def __next__(self):
if self.cur_idx >= len(self.obj.names):
raise StopIteration
ret = self.obj.names[self.cur_idx]
self.cur_idx += 1
return ret
class_mate = ClassMates()
class_mate.add('Curry')
class_mate.add('Klay')
for i in class_mate:
print(i)
可以将上面的两个类合并为一个类:
class ClassMates(object):
def __init__(self):
self.names = []
self.cur_idx = 0
def add(self,name):
self.names.append(name)
def __iter__(self):
return self
def __next__(self):
if self.cur_idx >= len(self.names):
raise StopIteration
ret = self.names[self.cur_idx]
self.cur_idx += 1
return ret
class_mate = ClassMates()
class_mate.add('Curry')
class_mate.add('Klay')
for i in class_mate:
print(i)