具体解释了怎么用迭代,怎样用迭代,怎样转换成迭代,可以看看
(一)
from collections.abc import Iterable
from collections.abc import Iterator
import time
class Person(object):
def __init__(self):
self.names = list()
self.current_num = 0
def add_person(self,name):
self.names.append(name)
def __iter__(self):
#pass
return PersonsIterator(self)
class PersonsIterator(object):
def __init__(self,obj):
self.obj = obj
self.current_num = 0
def __iter__(self):
pass
def __next__(self):
#pass
#return 12345
if self.current_num < len(self.obj.names):
ret = self.obj.names[self.current_num]
self.current_num += 1
#return self.obj.names[self.current_num]
return ret
else:
raise StopIteration
p1 = Person()
p1.add_person('张三')
p1.add_person('李四')
p1.add_person('王五')
p_iter = iter(p1)
while True:
try:
ret = next(p_iter)
print(ret)
except Exception:
break
运行结果:
(二)
from collections.abc import Iterable
from collections.abc import Iterator
import time
class Person(object):
def __init__(self):
self.names = list()
self.current_num = 0
def add_person(self,name):
self.names.append(name)
def __iter__(self):
#pass
return PersonsIterator(self)
class PersonsIterator(object):
def __init__(self,obj):
self.obj = obj
self.current_num = 0
def __iter__(self):
pass
def __next__(self):
#pass
#return 12345
if self.current_num < len(self.obj.names):
ret = self.obj.names[self.current_num]
self.current_num += 1
#return self.obj.names[self.current_num]
return ret
else:
raise StopIteration
p1 = Person()
p1.add_person('张三')
p1.add_person('李四')
p1.add_person('王五')
print(isinstance(p1,Iterable)) #判断是否可以迭代
# iter()的作用是调用p1的iter()方法
# next()的作用是调用迭代器的next方法
p_Iterator = iter(p1)
print(isinstance(p_Iterator,Iterator)) #判断是否为迭代器
for temp in p1:
print(temp)
time.sleep(1)
运行结果: