As you know
everything in python is an object. Python has a special protocol defined for
iterating through objects. This concept of protocol is a set of standard
defined so as to call an object an iterator (which can be iterated using python
standard defined next() method or using loops).
In Python,
iterator is any object which can be iterated using standard next() method or
using any loop which internally calls next() method. Any custom class defined
can be made iterator by defining next() method(in
python 2.7+) or __next__() method (in
python 3.4+) .
Next()
method uses class’s internal variable to track the current position of index
value to be returned when next() method is called on the class’s object.
class MyClass1(object):
lst = []
index = 0
def __init__(self):
self.lst = []
def __init__(self,l):
self.lst.extend(l)
def next(self):
try:
self.index = self.index+1
if self.index>=len(self.lst):
raise StopIteration
else:
return self.lst[self.index-1]
except:
print("error")
b = MyClass1([1,2,4])
try:
print(next(b))
print(next(b))
except:
print('b is not yet iterator')
except:
print('b is not yet iterator')
Output:
1
2
However
python’s list, sets etc are not an iterator. But it still allows to loop
through them. This is because these are iterables which can be converted to
iterators by calling python’s standard iter() method and passing the object for
list or sets through it. Internally list and set function implements __iter__()
method. Calling standard iter() method internally calls __iter__() method of
the class which returns an iterator object.
class MyClass1(object): lst = [] index = 0def __init__(self): self.lst = [] def __init__(self,l): self.lst.extend(l) def __iter__(self): return iter(self.lst) def next(self): try: self.index = self.index+1 if self.index>=len(self.lst): raise StopIteration else: return self.lst[self.index-1] except: print("error") b = MyClass1([1,2,4]) try: x = iter(b)print(next(x))print(next(x)) except: print('b is not yet iterable')Output:
1
2
No comments:
Post a Comment