>>> f = open('/etc/passwd')
>>> for line in reversed(list(f)):
... print(line,end='')
...
但是上述反转代码,在遇到大文本时,将耗费大量的内存。
自定义类的反转函数如下
>>> class C:
... def __init__(self,start):
... self.start = start
... def __iter__(self):
... n = self.start
... while n>0:
... yield n
... n -= 1
... def __reversed__(self):
... n =1
... while self.start>=n:
... yield n
... n +=1
...
>>>