Using an iterator in python?

前端 未结 4 915
[愿得一人]
[愿得一人] 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:35

    You need another variable to track the current number:

    def __init__(self, number):
        self.number = number
        self.current = 1
    

    Then you need to compare it with the ending number, and maybe increment it:

    def __next__(self):
        if self.current > self.number:
            raise StopIteration
        current = self.current
        self.current += 2
        return current
    

提交回复
热议问题