编程语言
首页 > 编程语言> > python 自定义MyRange 2(yield)

python 自定义MyRange 2(yield)

作者:互联网

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)

标签:__,自定义,python,self,number,yield,MyRange,skill,def
来源: https://blog.csdn.net/jialan75/article/details/121598194