'''
尝试设计一个类时,可以以遍历这个类产生的实例对象的时候
遍历所有的宠物名称
'''
class Pets:
def __init__(self):
self.count=0
def __iter__(self):
self.pets=["dog","cat","bird"]
return iter(self.pets) #返回迭代对象
def __next__(self):
if self.count>len(self.pets):
raise StopIteration("停止遍历")
else:
count+=1
p = Pets()
for i in p:
print(i)
Python_遍历__iter__和__next__配套使用
最新推荐文章于 2023-05-04 16:24:43 发布