from collections import Iterable
from collections import Iterator
import time
class Classmate(object):
current_num = 0
def __init__(self):
self.name = list()
def add(self, name):
self.name.append(name)
# 如果想要一个对象成为一个可迭代的对象,即可以使用for 那么必须实现__iter__方法
def __iter__(self):
# 返回这个对象必须有__next__方法
return ClassIterator(self)
class ClassIterator(object):
def __init__(self, obj):
self.obj = obj
def __iter__(self):
pass
def __next__(self):
if self.obj.current_num<len(self.obj.name):
ret = self.obj.current_num
self.obj.current_num += 1
return self.obj.name[ret]
else:
raise StopIteration
classmate = Classmate()
classmate.add("老王")
classmate.add("张三")
# 判断Classmate是否是可迭代类型
print("判断classmate是否可迭代", isinstance(classmate, Iterable))
classmate_iterator = iter(classmate)
print("判断classmate_iterator是否是可迭代对象", isinstance(classmate_iterator, Iterator))
print(next(classmate_iterator))
for n in classmate:
# 每调用一次都会调用classmate的__iter__方法返回值对象的__next__方法
print(n)
time.sleep(1)
E:\python_project\NetWork\venv\Scripts\python.exe E:/python_project/NetWork/协程/__init__.py
判断classmate是否可迭代 True
判断classmate_iterator是否是可迭代对象 True
老王
张三
Process finished with exit code 0
改进版的迭代器
from collections import Iterable
from collections import Iterator
import time
class Classmate(object):
current_num = 0
def __init__(self):
self.name = list()
def add(self, name):
self.name.append(name)
# 如果想要一个对象成为一个可迭代的对象,即可以使用for 那么必须实现__iter__方法
def __iter__(self):
# 返回这个对象必须有__next__方法
return self
def __next__(self):
if self.current_num < len(self.name):
ret = self.current_num
self.current_num += 1
return self.name[ret]
else:
raise StopIteration
classmate = Classmate()
classmate.add("老王")
classmate.add("张三")
# 判断Classmate是否是可迭代类型
print("判断classmate是否可迭代", isinstance(classmate, Iterable))
classmate_iterator = iter(classmate)
print("判断classmate_iterator是否是可迭代对象", isinstance(classmate_iterator, Iterator))
print(next(classmate_iterator))
for n in classmate:
# 每调用一次都会调用classmate的__iter__方法返回值对象的__next__方法
print(n)
time.sleep(1)