Iteration in Computer Programming is a control statement that allows the repetition of code. For loops, while loops and do while loops are examples of iteration. An iterator in Python is an object that implements the iterator interface which has the __iter__() and the __next__() method. This will allow the for in type of loop to be executed. An iterable is an object that returns an iterator via the iter method.
Here is an example that prints the table of 3.
class Table:
def __init__(self,n):
self.n=n
self.i=1
def __next__(self):
if self.i>10:
raise StopIteration
else:
value=self.n*self.i
self.i+=1
return value
def __iter__(self):
self.i=1
return self
t=Table(3)
for x in t:
print(x)
We can implement a reversed method to get a reversed iterator for a given iterator.
class Table:
def __init__(self,n):
self.n=n
self.i=1
self.direction = "Forward"
def __next__(self):
if self.i>10:
raise StopIteration
else:
value=self.n*self.i
self.i+=1
if self.direction=="Forward":
return value
else:
return self.n*11-value
def __iter__(self):
self.i=1
return self
def __reversed__(self):
self.direction = "Reverse"
self.i = 1
return self
t=Table(3)
for x in t:
print(x)
rt=reversed(t)
for x in rt:
print(x)
What happens if we want to use indexing?
For indexing we need to implement the __len__() and the __getitem__() methods. Here is the current code.
class Table:
def __init__(self,n):
self.n=n
self.i=1
self.direction = "Forward"
def __next__(self):
if self.i>10:
raise StopIteration
else:
value=self.n*self.i
self.i+=1
if self.direction=="Forward":
return value
else:
return self.n*11-value
def __iter__(self):
self.i=1
return self
def __reversed__(self):
self.direction = "Reverse"
self.i = 1
return self
def __len__(self):
return 10
def __getitem__(self,i):
return self.n*(i+1)
t=Table(3)
n=len(t)
for i in range(n):
print(t[i])
Please post a Query if you have any. Comments will be appreciated,
0 Comments