反向迭代与实现

要求:实现一个连续浮点数发生器FloatRange,根据给定范围和步进值产生一系列连续浮点数,如迭代FloatRange(3.0,4.0,0.2)可产生序列:
正向:3.0,3.2,3.4,3.6,3.8,4.0
反向:4.0,3.8,3.6,3.4,3.2,3.0

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:
            yield t
            t += self.step
    # 反向
    def __reversed__(self):
        r = self.end
        while r >= self.start:
            yield r
            r -= self.step

for x in FloatRange(1.0,4.0,0.5):
    print(x)
for x in reversed(FloatRange(1.0,4.0,0.5)):
    print(x)
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页