python---写一个迭代器

本文介绍了如何在Python中创建一个迭代器。通过定义一个名为`House`的类,该类具有`add_person`方法来添加数据,并实现了`__iter__`和`__next__`方法以支持迭代操作。在`main`函数中,展示了如何使用这个迭代器遍历并打印对象中的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 迭代器
class House(object):
    # 属性初始化
    def __init__(self, room):
        self.room = room  # 当前调用对象
        self.people = []  # 对象下所有的数据,用列表保存
        self.current_index = 0  # 当前遍历到的列表下标

    # 添加方法
    def add_person(self, person):
        self.people.append(person)

    # iter方法,并返回一个迭代器
    def __iter__(self):
        return self

    # next方法,返回当前记录的所在下标及相应数据
    def __next__(self):
        if self.current_index < len(self.people):
            current_data = self.people[self.current_index]
            self.current_index += 1
            return current_data
        else:
            self.current_index = 0
            raise StopIteration


def main():
    """一个可迭代对象同时又是迭代器"""
    # 创建一个类对象
    bedroom = House('bedroom')

    # 适用对象可以添加数据
    bedroom.add_person('xiaoli')
    bedroom.add_person('maomao')
    # 使用for遍历该对象
    for person in bedroom:
        print(person)

if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值