Skip to content

Instantly share code, notes, and snippets.

@SamuraiT
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamuraiT/9182293 to your computer and use it in GitHub Desktop.
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
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()
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