Created
June 5, 2020 08:33
-
-
Save StephenFordham/6d5a250bd2b721b6099ab650a481f1d5 to your computer and use it in GitHub Desktop.
custom_iterator_object
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
class CustomIterTeams(object): | |
def __init__(self, division, teams=[]): | |
self._mng = division | |
self._teams = teams | |
self._index = -1 | |
def __iter__(self): | |
return self | |
# def __iter__(self): | |
# return (t for t in self._teams) | |
def __next__(self): | |
self._index += 1 | |
if self._index >= len(self._teams): | |
self._index = -1 | |
raise StopIteration | |
else: | |
return self._teams[self._index] | |
def __reversed__(self): | |
return self._teams[::-1] | |
prem_teams = CustomIterTeams('Premier League', ['Arsenal', 'Watford', 'Bournemouth', 'Man Utd', 'Liverpool']) | |
for t in prem_teams: | |
print(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a buggy implementation.
Try doing this :
SOLUTION :
This is the correct way to ensure that iterable object can be used multiple times.
https://stackoverflow.com/questions/21665485/how-to-make-a-custom-object-iterable