自定义类,写上__iter__和__reversed__ 方法,赋予正反遍历方法

class FloatRange:
    def __init__(self, start, end, step=0.1):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        t = self.start
        while t <= self.end:
            print(t, 'iter')
            yield t
            t += self.step

    def __reversed__(self):
        t = self.end
        while t >= self.start:
            print(t, 'reversed')
            yield t
            t -= self.step

# for x in reversed(FloatRange(1.0, 4.0, 0.5)):
#     # print x
#     pass


for x in FloatRange(1.0, 4.0, 0.2):
    # print x
    pass
posted @ 2022-05-25 23:45  ty1539  阅读(21)  评论(0编辑  收藏  举报