实现一个连续浮点数发生器FloatRange,产生一些连续浮点数。
实现反向迭代协议的__reversed__方法,它返回一个迭代器。
1 class FloatRange: 2 def __init__(self,start,end,step = 0.1): 3 self.start = start 4 self.end = end 5 self.step = step 6 7 def __iter__(self): 8 t = self.start 9 while t <= self.end: 10 yield t 11 t += self.step 12 13 def __reversed__(self): 14 t = self.end 15 while t >= self.start: 16 yield t 17 t -= self.step 18 19 if __name__ == "__main__": 20 21 for x in FloatRange(1.0,4.0,0.5): 22 print x 23 24 for x in reversed(FloatRange(1.0,4.0,0.5)): 25 print x 26