【原文链接】
Iterable,可迭代:
一个类实现了__iter__()函数,则这个类是可迭代的,通常__iter__()函数必须返回一个
实现了__next__()的类的对象,当然如果自己实现了__next__(),也可以返回自己
Iterator 迭代器:
同时实现了__iter__()和__next__()的对象,就是迭代器
class Student():
def __init__(self,name):
self.name=name
self.start=0
def __iter__(self):
return self
def __next__(self):
if self.start <len(self.name):
result=self.name[self.start]
self.start+=1
return result
else:
raise StopIteration
s=Student("Jack Macial")
for elem in s:
print(elem)
执行结果如下:
J
a
c
k
M
a
c
i
a
l
下面查看next函数的使用
class Student():
def __init__(self,name):
self.name=name
self.start=0
def __iter__(self):
return self
def __next__(self):
if self.start <len(self.name):
result=self.name[self.start]
self.start+=1
return result
else:
raise StopIteration
s=Student("Jack Macial")
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
执行结果如下:
J
a
c
k
M
a
c
i
a
l
Traceback (most recent call last):
File "G:/python_flask/test.py", line 29, in <module>
print(next(s))
File "G:/python_flask/test.py", line 15, in __next__
raise StopIteration
StopIteration