标签:__iter__ sel info 自定义 for code int next 定义类
一、
class Foo: def __init__(self,n): self.n = n def __iter__(self): return self def __next__(self): if self.n == 13: raise StopIteration self.n += 1 return self.n f1 = Foo(10) for i in f1: #obj = iter(f1)---->f1.__iter__() print(i) #obj.__next__()
二、迭代器实现斐波那契额数列
class Fib: def __init__(self): self._a = 1 self._b = 1 def __iter__(self): return self def __next__(self): if self._a > 100: raise StopIteration self._a, self._b = self._b, self._a + self._b return self._a f1 = Fib() print(next(f1)) print(next(f1)) print("----------->") for i in f1: print(i)
标签:__iter__ sel info 自定义 for code int next 定义类
原文地址:https://www.cnblogs.com/dabai123/p/11629013.html