EDIT: for 2.7 instead of 3
Here is my understanding
In below example code, we can say that class Testing is an iterable object because we implemented it with __iter__
. Method __iter__
returns an iterator. The iterator uses the next method to determine the next value on the iteration. If I were to remove the next
method from the class below, the code would fail.
iterable = an object that can be iterated over...implemented with __iter__
iterator = object that defines how to iterate...literally, what is the next value. This is implemented with __next__
So the piece of code you questioned actually takes the class object (self is the argument) and returns an iterator, which makes the class object iterable. So in the example below we can actually iterate over the class object myObj.
class Testing:
def __init__(self,a,b):
self.a = a
self.b = b
def __iter__ (self):
return self
def next(self):
if self.a <= self.b:
self.a += 1
return self.a-1
else:
raise StopIteration
myObj = Testing(1,5)
for i in myObj:
print i
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…