Build a Basic Python Iterator

前端 未结 10 1222
南旧
南旧 2020-11-21 12:22

How would one create an iterative function (or iterator object) in python?

10条回答
  •  滥情空心
    2020-11-21 12:37

    This question is about iterable objects, not about iterators. In Python, sequences are iterable too so one way to make an iterable class is to make it behave like a sequence, i.e. give it __getitem__ and __len__ methods. I have tested this on Python 2 and 3.

    class CustomRange:
    
        def __init__(self, low, high):
            self.low = low
            self.high = high
    
        def __getitem__(self, item):
            if item >= len(self):
                raise IndexError("CustomRange index out of range")
            return self.low + item
    
        def __len__(self):
            return self.high - self.low
    
    
    cr = CustomRange(0, 10)
    for i in cr:
        print(i)
    

提交回复
热议问题