一、简单示例
死循环
class Foo:
def __init__(self, x):
self.x = x
def __iter__(self):
return self
def __next__(self):
self.x += 1
return self.x
f = Foo(3)
for i in f:
print(i)
二、StopIteration异常版
加上StopIteration异常
class Foo:
def __init__(self, start, stop):
self.num = start
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.num >= self.stop:
raise StopIteration
n = self.num
self.num += 1
return n
f = Foo(1, 5)
from collections import Iterable, Iterator
print(isinstance(f, Iterator))
#输出
True
for i in Foo(1, 5):
print(i)
#输出
1
2
3
4
三、模拟range
class Range:
def __init__(self, n, stop, step):
self.n = n
self.stop = stop
self.step = step
def __next__(self):
if self.n >= self.stop:
raise StopIteration
x = self.n
self.n += self.step
return x
def __iter__(self):
return self
for i in Range(1, 7, 3):
print(i)
#输出
1
4
四、斐波那契数列
class Fib:
def __init__(self):
self._a = 0
self._b = 1
def __iter__(self):
return self
def __next__(self):
self._a, self._b = self._b, self._a + self._b
return self._a
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
f1 = Fib()
for i in f1:
if i > 100:
break
print('%s ' % i, end='')
#输出
1 1 2 3 5 8 13 21 34 55 89
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/213549.html