Created
May 28, 2020 20:48
-
-
Save ZhouYang1993/3ea47925c84261b2042aa8411af356f9 to your computer and use it in GitHub Desktop.
Iterators in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections.abc import Iterable, Iterator | |
| class Fib(object): | |
| def __init__(self): | |
| self.a, self.b = 0, 1 | |
| def __iter__(self): | |
| return self | |
| def __next__(self): | |
| self.a, self.b = self.b, self.a + self.b | |
| if self.a > 1000: # set a limitation to stop | |
| raise StopIteration() | |
| return self.a | |
| f = Fib() | |
| print(isinstance(f, Iterator)) | |
| print(next(f)) | |
| print(next(f)) | |
| print(next(f)) | |
| print(next(f)) | |
| # True | |
| # 1 | |
| # 1 | |
| # 2 | |
| # 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment