Python学习日常记录,迭代器–在类外面遍历类里面的列表
日常记录,防止遗忘。
'''
应用场景:
在类中定义了一个列表,需要在类外面遍历列表中的元素
方法实现:
需要使用迭代器,迭代器中必定会包含iter和next方法
当一个类中有iter和next两个方法的时候那这个类必定是一个迭代器,如果只有iter,只能是一个可迭代的对象
运行流程:
1,for循环启动后,先判断classmate是否为可迭代对象,此时需要用到iter函数,for会自动调用,如果没有该方法,会报错为不可迭代对象
2,调用iter函数后,for循环判断当前为可迭代对象,使用next函数,next函数返回什么,就会打印什么
'''
import time
from collections.abc import Iterable #判断当前对象是否可用迭代(遍历)
from collections.abc import Iterator #判断当前对象是否为迭代器,迭代器是指存放迭代对待的容器,比如列表,元组等
class Classmate(object):
def __init__(self):
self.names = list()
self.current_num = 0
def add(self,name):
self.names.append(name)
def __iter__(self):
'''要想在类外部访问类里面的列表,需要使用iter方法让for循环在遍历的时候能够使用到该方法,
Python作为高级语言,我们只需要在有列表的类中定义该方法即可,for循环会自动调用该方法'''
return self #使用self将Classmate传递给ClassIterator的ojb
def __next__(self):
'''for循环会自动调用next方法,这里直接返回列表即可'''
if self.current_num < len(self.names): #防止列表越界
ret = self.names[self.current_num]
self.current_num += 1
return ret
#在迭代器中,当for循环取出所有数值后并不会结束,会一直在运行,没有值就会显示None,
# 此时需要抛出一个异常告诉for循环迭代器中已经没有对象,可以结束循环,使用 raise StopIteration (这里为固定语法)
else:
raise StopIteration
classmate = Classmate()
classmate.add('老王')
classmate.add('王二')
classmate.add('张三')
# isinstance(要判断的对象,Iterable)方法,Iterable 为语法中的参数,判断是否为迭代对象,返回布尔值
print('判断classmate是否为可以迭代的对象: ', isinstance(classmate,Iterable))
#将classmate传入iter方法,重新赋值判断对象是否为迭代器,注意 这里是判断是否为迭代器,isinstance里面需要使用Iterator
classmate_iterator = iter(classmate)
print('判断classmate_iterator是否为迭代器: ', isinstance(classmate_iterator,Iterator))
for name in classmate:
print(name)
time.sleep(1)