迭代器:
from collections import Iterable
from time import sleep
# 判断是否是一个可迭代的对象
# print(isinstance([11, 22], Iterable))
class Classmate(object):
def __init__(self):
self.names = list()
self.num = 0
def add_name(self, name):
self.names.append(name)
# 迭代器--->有__iter__和__next__两个方法的类叫迭代器
def __iter__(self):
"""如果想要一个对象成为一个 可迭代的对象,即 可以使用for,则必须实现__iter__方法"""
# 返回时 自动创建Classiterator对象,并把Classmate类中的self传递给Classiterator,执行Classiterator中的next方法
return self # 返回自己本身
def __next__(self):
if self.num < len(self.names):
re = self.names[self.num]
self.num += 1
return re
else:
raise StopIteration
if __name__ == '__main__':
classmate = Classmate()
classmate.add_name("老王")
c