ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 对象迭代 ~~~ for temp in xxx_obj: pass ~~~ 1. 判断xx_obj是否是可以迭代 2. 调用iter函数,得到xx_obj对象的`__iter__`方法的返回值 3. `__iter__`方法的返回值是一个迭代器 # 判断是否可迭代和迭代器 ~~~ from collections import Iterable from collections import Iterator class Classmate(object): def __init__(self): self.name = list() def add(self, name): self.name.append(name) def __iter__(self): return ClassIterator() class ClassIterator(object): def __iter__(self): pass def __next__(self): pass classmate = Classmate() classmate.add('老王') classmate.add('王二') classmate.add('张三') print('判断classmate是否是可以迭代的对象:', isinstance(classmate, Iterable)) classmate_iterator = iter(classmate) print('判断classmate_iterator是否是迭代器:', isinstance(classmate_iterator, Iterator)) ~~~ # 完善迭代器 ~~~ from collections import Iterable from collections 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): """如果想要一个对象成为一个可迭代的对象,即可以使用for,那么必须实现__iter__方法""" return self def __next__(self): if self.current_num < len(self.names): ret = self.names[self.current_num] self.current_num += 1 return ret else: raise StopIteration classmate = Classmate() classmate.add('老王') classmate.add('王二') classmate.add('张三') for name in classmate: print(name) ~~~