python中实现可迭代对象的方法

当对元组,列表,字典,集合,字符串使用for循环语句的时候,可以依次拿到里面的数据,这样的过程称为遍历,也叫迭代。

想要让创建出来的类的实例对象可以迭代,也就是可以使用for来遍历,需要在类中实现__iter__方法,需要实现__next__方法。

class Classmates():
    def __init__(self):
        self.name = []
        self.current_num = 0
    def add(self, name):
        self.name.append(name)

    def __iter__(self):
        return self  

    def __next__(self):
        if self.current_num < len(self.name):
            ret = self.name[self.current_num]
            self.current_num += 1
            return ret
        else:
            raise StopIteration  # 抛出异常停止遍历

classmate = Classmates()
classmate.add("张三")
classmate.add("李四")
classmate.add("王五")
for name in classmate:
    print(name)

猜你喜欢

转载自www.cnblogs.com/xifengmo/p/11029391.html