I'm trying to create my own class for an iterator and found such an example:
class OddNum:
"""Class to implement iterator protocol"""
def __init__(self, num = 0):
self.num = num
def __iter__(self):
self.x = 1
return self
def __next__(self):
if self.x <= self.num:
odd_num = self.x
self.x += 2
return odd_num
else:
raise StopIteration
for num in OddNum(10):
print(num)
the output is: 1 3 5 7 9
Now, if I remove the row odd_num = self.x and change return odd_num to return self.x, I get the following output: 3 5 7 9 11
What is the difference between the 2 codes, why should I define a variable to self.x?
self.xfrom after adding on 2 rather than before doing so. So the difference is 2.self.xbefore you have a chance to return the initial value.self.x = -1, so thatself.x += 2produces the first odd number.