Python编程举例-iter和next结合定制可迭代对象

class Foo:
    def __init__(self,n):
        self.n = n
    def __iter__(self):
        return self
    def __next__(self):
        if self.n == 15:
            raise StopIteration('终止了')
        self.n +=1
        return self.n

f1 = Foo(10)
print(f1.__next__())
print(f1.__next__())
print(next(f1))
print(next(f1))

for i in f1: #调用对象的Iter方法iter(f1)--->f1.__iter__() 
    print(i)#Iter的本质是去调用next方法
原文地址:https://www.cnblogs.com/konglinqingfeng/p/9657372.html