Last active
October 2, 2015 14:23
-
-
Save apalii/93b0fcc047e6c5f77bcc to your computer and use it in GitHub Desktop.
Iteration protocol
This file contains 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
# --- iterators --- | |
# Если у объекта есть методы __iter__() __next__() значит он является итератором | |
class MyIter(object): | |
def __init__(self, start, stop): | |
self._current = start | |
self._stop = stop | |
def __iter__(self): | |
return self | |
def __next__(self): | |
if self._current < self._stop: | |
result = self._current | |
self._current += 1 | |
return self._current | |
raise StopIteration | |
q = MyIter(0, 5) | |
qq = iter(q) | |
next(qq) | |
# ------------------------------------------------- | |
class ExampleIterator: | |
def __init__(self, data): | |
self.index = 0 | |
self.data = data | |
def __iter__(self): | |
return self | |
def __next__(self): | |
if self.index >= len(self.data): | |
raise StopIteration | |
result = self.data[self.index] | |
self.index += 1 | |
return result | |
class ExampleIterable: | |
def __init__(self, data): | |
self.data = data | |
def __iter__(self): | |
return ExampleIterator(self.data) | |
[i**2 for i in ExampleIterable([1,2,3])] | |
[1, 4, 9] | |
# F O R vs W H I L E | |
product = 1 | |
for i in [1,2,3,4]: | |
product *= i | |
print(product) | |
product = 1 | |
i = iter([1,2,3,4]) | |
while True: | |
try: | |
product *= next(i) | |
except StopIteration: | |
break | |
print(product) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment