美文网首页
python 中实现对象的反向迭代

python 中实现对象的反向迭代

作者: 北冢 | 来源:发表于2017-12-11 20:35 被阅读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):
        t = self.end
        while t >= self.start:
            yield t
            t -= self.step


print("=====正向迭代=====")            
for x in FloatRange(1.0, 4.0, 0.5):
    print(x)
    
print("=====反向迭代=====")
for x in reversed(FloatRange(1.0, 4.0, 0.5)):
    print(x)

相关文章

网友评论

      本文标题:python 中实现对象的反向迭代

      本文链接:https://www.haomeiwen.com/subject/kmewixtx.html