reverse iterator

    To implement a reverse iterator is actually very simple, just implement the special method __reversed__, which will be called by python's built-in reversed function. Reverse iterators can improve code performance when there is a large amount of data, because it does not need to populate a list with data and then reverse iterate over the list.
    The following example is a simple analog of the built-in function 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)

    Run the example:
>>> 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
>>>

    The reason why the parameters are limited to integers rather than arbitrary real numbers here is mainly because the precision of floating-point numbers can make the code bloated.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327049753&siteId=291194637