Last active
August 29, 2015 13:56
-
-
Save SamuraiT/9182293 to your computer and use it in GitHub Desktop.
counter.py is a counter iterator that counts a number. gen_counter.py is counter which is implemented with a generator
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 Counter(object): | |
"""a counter iterator that counts a number | |
when you invoke the (next) method""" | |
def __init__(self): | |
self.count = 0 | |
def __iter__(self): | |
return self | |
def next(self): | |
self.count += 1 | |
return self.count | |
def main(): | |
count = Counter() | |
print next(count) # > 1 | |
print next(count) # > 2 | |
print "\n iteration starts \n" | |
for i in count: | |
print i | |
if i == 10:break | |
if __name__ == '__main__': | |
main() |
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 Counter(object): | |
"""a counter iterator that counts a number | |
when you invoke the (iter) method which generates a generator""" | |
def __init__(self): | |
self.count = 0 | |
def __iter__(self): | |
while True: | |
self.count += 1 | |
yield self.count | |
def main(): | |
count = Counter() | |
print "\n iteration starts \n" | |
for i in count: | |
print i | |
if i == 10:break | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment