Skip to content

Instantly share code, notes, and snippets.

@hygull
Created February 14, 2017 13:03
Show Gist options
  • Select an option

  • Save hygull/71f29062315f9be8920b0e11f477ec9a to your computer and use it in GitHub Desktop.

Select an option

Save hygull/71f29062315f9be8920b0e11f477ec9a to your computer and use it in GitHub Desktop.
creating our own python iterator created by hygull - https://repl.it/FjID/0
"""
Coded On : 14 Feb 2014.
Aim : To create our own iterator in Python.
Reference link : http://stackoverflow.com/questions/19151/build-a-basic-python-iterator
"""
class Range:
def __init__(self,start,end): #constructor
self.start = start
self.end = end
def __iter__(self): #It's implicitly called after __init__()
return self
def next(self): #__next__() in Python3, it's called implicitly in each iteration(it is like condition testing handler)
if self.start > self.end:
raise StopIteration
else:
self.start+=1
return self.start-1
class Range2:
def __init__(self,start,end):
print "Initializing start & end..."
self.start = start
self.end = end
print "start & end initialized..."
def __iter__(self):
print "returning self..."
return self
def next(self): #__next__() in Python3
print "next is called..."
if self.start > self.end:
raise StopIteration
else:
self.start+=1
return self.start-1
for i in Range(1,10):
print i
print "\n"
for i in Range2(1,10):
print i
"""
admins-MacBook-Pro-3:js-basics admin$ python ~/Desktop/counter.py
1
2
3
4
5
6
7
8
9
10
Initializing start & end...
start & end initialized...
returning self...
next is called...
1
next is called...
2
next is called...
3
next is called...
4
next is called...
5
next is called...
6
next is called...
7
next is called...
8
next is called...
9
next is called...
10
next is called...
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment