标签:案例 blog __iter__ reverse log title .com python 3.2
# 有关列表问题,参考:Python:列表list
案例:
需求:实现一个连续浮点数发生器FloatRange(和range类似),根据给定范围(start,end)和步进值(step),产生一系列连续的浮点数;
如迭代FlartRange(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 __reversed__(self): t = self.end while t >= self.start: yield t t -= self.step def __iter__(self): t = self.start while t <= self.end: yield t t += self.step # 此循环,实例化时自动调用__iter__()方法,而不是__reversed__()方法; for x in FloatRange(1.0, 3.0, 0.5): print(x) # 此循环,只有定义了__reversed__()方法后,才能直接使用reversed; for x in reversed(FloatRange(1.0, 4.0, 0.5)): print(x)
标签:案例 blog __iter__ reverse log title .com python 3.2
原文地址:https://www.cnblogs.com/volcao/p/8757385.html