Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created May 28, 2020 20:48
Show Gist options
  • Save ZhouYang1993/3ea47925c84261b2042aa8411af356f9 to your computer and use it in GitHub Desktop.
Save ZhouYang1993/3ea47925c84261b2042aa8411af356f9 to your computer and use it in GitHub Desktop.
Iterators in Python
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