使用生成器功能,可以通过documentation实现python run.py
的方式:
itertools.count
我试图找到一种没有生成器功能的类似迭代器。
def count(start=0, step=1):
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) -> 2.5 3.0 3.5 ...
n = start
while True:
yield n
n += step
这是实现吗?
可以肯定的是,这没有任何实际意义,重点只是要了解如何使用生成器来实现。
答案 0 :(得分:1)
您可以使用collections.abc.Iterator
以更少的代码实现计数
from collections.abc import Iterator
class count(Iterator):
def __init__(self, start=0, step=1):
self.c, self.step = start-step, step
def __next__(self):
self.c += self.step
return self.c
答案 1 :(得分:0)
最佳实践之一是编写一个小型单元测试。您可以为此使用unittest框架。
这是一个包含多个测试的示例,这些测试在循环中使用您的类并检查迭代器的值:
import unittest
import random
class TestCount(unittest.TestCase):
loops = 20
def test_default(self):
c = Count()
for i in range(self.loops):
self.assertEqual(i, next(c))
def test_start(self):
start = random.randint(-10, 10)
c = Count(start=start)
for i in range(start, start + self.loops):
self.assertEqual(i, next(c))
def test_step_pos(self):
step = random.randint(1, 5)
c = Count(step=step)
for i in range(0, self.loops, step):
self.assertEqual(i, next(c))
def test_step_neg(self):
step = random.randint(-5, -1)
c = Count(step=step)
for i in range(0, -self.loops, step):
self.assertEqual(i, next(c))