一般认为迭代器就是实现了两个方法__iter__和__next__
- 先创建这样一个类
from collections import Iterable from collections import Iterator class classiterable(object): def __iter__(self): pass def __next__(self): pass class mycoach(object): def __init__(self): pass def addname(self): pass def __iter__(self): return classiterable() cpc = mycoach() print("类对象可以被迭代" if isinstance(cpc,Iterable) else "无法被迭代")
输出结果:
类对象可以被迭代
通过在mycoach类的方法__iter__中返回classiterable实现了mycoach和classiterable类之间的联系
- 实现classiterator访问mycoach类中的属性
from collections import Iterable from collections import Iterator class classiterable(object): def __init__(self,obj): self.obj = obj self.count = 0 #添加一个计数器,确保按顺序遍历数组 def __iter__(self): pass def __next__(self): #防止迭代过头 if self.count<len(self.obj.coachname): ret = self.obj.coachname[self.count] self.count+=1 return ret else: raise StopIteration class mycoach(object): def __init__(self): self.coachname=[] def addname(self,name): self.coachname.append(name) def __iter__(self): return classiterable(self) cpc = mycoach() cpc.addname(‘陈培昌‘) cpc.addname(‘程劲‘) cpc.addname(‘徐晓冬‘) for i in cpc: print(i) print("类对象可以被迭代" if isinstance(cpc,Iterable) else "无法被迭代")
输出结果:
陈培昌 程劲 徐晓冬 类对象可以被迭代
- 完全进化版本---mycoach内部实现__next__魔术方法
class mycoach(object): def __init__(self): self.coachname=[] self.count=0 def addname(self,name): self.coachname.append(name) def __iter__(self): return self def __next__(self): if self.count<len(self.coachname): ret = self.coachname[self.count] self.count+=1 return ret else: raise StopIteration cpc = mycoach() cpc.addname(‘陈培昌‘) cpc.addname(‘程劲‘) cpc.addname(‘徐晓冬‘) for i in cpc: print(i) print("类对象可以被迭代" if isinstance(cpc,Iterable) else "无法被迭代")
输出结果:
陈培昌 程劲 徐晓冬 类对象可以被迭代
原文地址:https://www.cnblogs.com/saintdingspage/p/11621820.html
时间: 2024-10-10 18:28:13