Python 迭代器对象iterator
作者:互联网
(1) 定义:可以被next()函数调用并返回下一个值的对象。
(2) 语法
class 迭代器类名:
def __init__(self, 聚合对象):
self.聚合对象= 聚合对象
def __next__(self):
if 没有元素:
raise StopIteration
return 聚合对象元素
遍历商品控制器
class CommodityController:
pass
controller = CommodityController()
controller.add_commodity("铅笔")
controller.add_commodity("倚天剑")
controller.add_commodity("奥特曼")
for item in controller:
print(item)
class CommodityIierator:
def __init__(self, list_iterator):
self.list_iterator= list_iterator
self.i=0
def __next__(self):
if self.i>=len(self.list_iterator):
raise StopIteration
item=self.list_iterator[self.i]
self.i+=1
return item
class CommodityController:
def __init__(self):
self.__list_commodity=[]
def __iter__(self):
return CommodityIierator(self.__list_commodity)
def add_commodity(self,item):
self.__list_commodity.append(item)
passcontroller = CommodityController()
passcontroller.add_commodity("铅笔")
passcontroller.add_commodity("倚天剑")
passcontroller.add_commodity("奥特曼")
for item in passcontroller:
print(item)
标签:__,iterator,迭代,Python,commodity,self,list,item,add 来源: https://blog.csdn.net/Zohn_Sun/article/details/122761237