Python中使用迭代器的方式输出斐波那契数列

拥有__iter__方法和__next__方法的对象就是迭代器

class Fib(): # 创建一个类
    def __init__(self,num): # 初始化方法
        self.num=num
        self.a=1
        self.b=1
        self.current=1
    def __iter__(self): # __iter__在这个列表里返回它本身
        return self
    def __next__(self): # 判断对象是否可迭代
        if self.current<=self.num:
            temp=self.a # 定义一个变量temp
            self.a,self.b=self.b,self.a+self.b
            self.current+=1
            return temp # 返回temp变量
        else:
            raise StopIteration # 停止迭代
for x in Fib(12): # 可迭代的对象通过for循环来输出它的值
    print(x)

你可能感兴趣的:(日常总结)