Skip to content

Instantly share code, notes, and snippets.

@keyo
Created September 7, 2011 14:05
Show Gist options
  • Save keyo/1200640 to your computer and use it in GitHub Desktop.
Save keyo/1200640 to your computer and use it in GitHub Desktop.
Python useless counter class
class Counter(object):
""" This class counts stuff... """
def __init__(self, start = 0, end = 10, increment = 1):
self.start = start
self.end = end
self.increment = increment
def __iter__(self):
# this method is called when a Counter object is used as an iterator (e.g. in a for loop).
i = self.start
while i < self.end:
yield i
i += self.increment
def __reversed__(self):
i = self.end
while i > self.start:
i -= self.increment
yield i
def __str__(self):
return str(map(str,self))
#instantiate a new Counter object, counting even numbers only
c = Counter(start = 0, end = 20, increment = 2)
print("As string")
print c
print("Forward iterator, comma separated")
#map each value from c into the str function to get a list of printable strings.
print ",".join(map(str,c))
print("Backward")
#reversed(c) gets an iterator from Counter.__reversed__ instead of Counter.__iter__
print map(str,reversed(c))
print("Loop")
for x in c:
print x
print("List comprehension of numbers divisible by 3")
print([x for x in c if x % 3 == 0 ])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment