下面这个示例是对内置函数 range 的简单模拟:
class Countdown: def __init__(self, start, stop, step=1): if not (isinstance(start, int) and isinstance(stop, int) and isinstance(step, int)): raise TypeError("All arguments need to be integers.") self._start = start self._stop = stop self._step = step def __iter__(self): n = self._start if self._step > 0: while n < self._stop: yield n n += self._step else: while n > self._stop: yield n n += self._step raise StopIteration def __reversed__(self): return Countdown(self._stop-1, self._start-1, -self._step)
运行示例:
>>> for i in Countdown(1.1, 8.2): print(i) Traceback (most recent call last): File "<pyshell#53>", line 1, in <module> for i in Countdown(1.1, 8.2): File "<pyshell#50>", line 4, in __init__ raise TypeError("All arguments need to be integers.") TypeError: All arguments need to be integers. >>> >>> for i in Countdown(1, 8, 2): print(i) 1 3 5 7 >>> >>> for i in reversed( Countdown(1, 8, 2) ): print(i) 7 5 3 1 >>>
这里之所以限制参数为整数而非任意实数,主要是因为浮点数的精度问题会让代码变得比较臃肿。