I have tried with this code to implement iterator protocol, and every thing works fine.
Ideally it shouldn't as I have not implemeted iter().
class PowerofTwo():
def __init__(self,maxi):
self.max = maxi
self.num = 0
def __next__(self):
if self.num < self.max:
result = 2 ** self.num
self.num += 1
return result
else:
raise StopIteration
myObj = PowerofTwo(5)
print(type(myObj)) #print <class '__main__.PowerofTwo'>
print(next(myObj)) #print 1
Even if assume that __iter__() method is available by default like __init__().
But not able to understand how can I directly call next() and skip calling iter(obj) at first place.
If I try same thing with list or other builtin iterator, I gets error that object is not an iterator.
Am I missing something basic here ?
__next__is exactly the method that thenext()function tries to call, and your class has a__next__method. Why do you expect it not to work?PowerofTwois an iterator, but it is not iterable. An iterable is something you can pass toiter; an iterator is the thing thatiterreturns and can be passed tonext.open, are both iterable and iterators. Others, likelist, are iterable, but not iterators.iter([1,2,3])returns not the list, but a value of typelist_iterator.__iter__, but it doesn't have to do anything other than returnself.