一、正向迭代器实现__iter__方法
二、反向迭代器实现__reversed__方法
三、实例:
from decimal import Decimal
class FloatRange:
def __init__(self, a, b, step):
self.a = Decimal(str(a))
self.b = Decimal(str(b))
self.step = Decimal(str(step))
def __iter__(self):
t = self.a
while t <= self.b:
yield t
t += self.step
def __reversed__(self):
t = self.b
while t >= self.a:
yield t
t -= self.step
fr = FloatRange(3.0, 4.0, 0.2)
print(fr, reversed(fr))
for i in fr:
print(i)
print("*"*20)
for x in reversed(fr):
print(x)