Skip to content

Instantly share code, notes, and snippets.

@digitalresistor
Created November 19, 2015 16:44
Show Gist options
  • Save digitalresistor/3c901e655d1b68f97f24 to your computer and use it in GitHub Desktop.
Save digitalresistor/3c901e655d1b68f97f24 to your computer and use it in GitHub Desktop.
class Counter:
def __init__(self, high):
self.current = 0
self.highest = high
# This class is now considered and iterable because of this special function
def __iter__(self):
return self
def next(self):
if self.current > self.highest:
raise StopIteration
else:
self.current += 1
return self.current - 1
def add_all(items):
a = 0
for i in items: # This implicitly turns the argument into an iterable
a = a + i
return i
print add_all([1, 2, 3, 4, 5, 6]) # using a list
print add_all((1, 2, 3, 4, 5, 6)) # using a tuple
print add_all(Counter(6)) # Using an object
# The add_all function doesn't care, so long as it's argument is an iterable of some sort, it will do the right thing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment