要实现一个反向迭代器其实非常简单,只需实现 __reversed__ 这个特殊方法即可,它会被 python 内置的 reversed 函数所调用。反向迭代器在数据量很多时可以改善代码性能,因为它不需要把数据填充到一个列表中然后再去反向迭代该列表。
下面这个示例是对内置函数 range 的简单模拟:
运行示例:
这里之所以限制参数为整数而非任意实数,主要是因为浮点数的精度问题会让代码变得比较臃肿。
下面这个示例是对内置函数 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
>>>
这里之所以限制参数为整数而非任意实数,主要是因为浮点数的精度问题会让代码变得比较臃肿。