Last active
May 3, 2016 21:05
-
-
Save gatspy/6280ae2981cc34b76bd9911f183e4263 to your computer and use it in GitHub Desktop.
python -- iterator
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
class SkipIterator(object): | |
def __init__(self, wrapped): | |
self.wrapped = wrapped | |
self.offset = 0 | |
def __next__(self): | |
if self.offset == len(self.wrapped): | |
raise StopIteration | |
else: | |
item = self.wrapped[self.offset] | |
self.offset += 2 | |
return item | |
def __iter__(self): | |
return self | |
def next(self): | |
return self.__next__() | |
class IterObject(object): | |
def __init__(self, wrapped): | |
self.wrapped = wrapped | |
def __iter__(self): | |
return SkipIterator(self.wrapped) | |
class IterAll(object): | |
def __init__(self, data): | |
self._data = data | |
def __iter__(self): | |
print 'iterator' | |
self._index = 0 | |
return self | |
def __next__(self): | |
if self._index == len(self._data): | |
raise StopIteration | |
item = self._data[self._index] | |
self._index += 1 | |
return item | |
def next(self): | |
return self.__next__() | |
def __getitem__(self, index): | |
print 'indexed from get item' | |
return self._data[index] | |
def __contains__(self, value): | |
return value in self._data | |
if __name__ == '__main__': | |
l = IterObject('abcdef') | |
print [x + y for x in l for y in l] | |
# print l | |
it = IterAll([1, 2, 3, 4, 5, 6, 7]) | |
print [x for x in it] | |
print it[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment