class MyRange:
def __init__(self, stop):
self.__stop = stop
def __iter__(self):
# yield 作用:将下列代码改为迭代器模式的代码
# 生成迭代器代码 的的大致规则
# 1.将yield以前的语句定义在next方法中
# 2.将yield后面的数据作为next方法返回值
number = 0
while number < self.__stop:
yield number
number += 1
##########以下代码是相等的##################
# number = 0
# while number < 3:
# yield number
# number += 1
#
# yield 0
# yield 1
# yield 2
for i in MyRange(3):
print(i)
##################以下是对象###########################################
class Skill:
def __init__(self, a):
self.a = a
class SkillManager:
def __init__(self):
self.__list = []
def add_skill(self, skill):
self.__list.append(skill)
def __iter__(self):
for item in self.__list:
yield item
manager = SkillManager()
manager.add_skill(Skill(2))
manager.add_skill(Skill(3))
manager.add_skill(Skill(4))
for item in manager:
print(item.a)