Using an iterator in python?

前端 未结 4 944
[愿得一人]
[愿得一人] 2021-01-21 16:05

I have just learned about iterators in Python however I am having a hard time implementing them.

I am trying to write a class to so that this loop works:



        
4条回答
  •  灰色年华
    2021-01-21 16:33

    Your object needs to keep track of its state and update it when __next__ is called.

    class OddNumbers(object):
        def __init__(self, number):
            self.current = ...
            self.number = number
    
        def __iter__(self):
            return self
    
        def __next__(self):
            # Update self.current
            # If the limit has been reached, raise StopIteration
            # Otherwise, return something
    

提交回复
热议问题