| 1 | # Example of an object implementing both forward and reversed iterators |
| 2 | |
| 3 | class Countdown: |
| 4 | def __init__(self, start): |
| 5 | self.start = start |
| 6 | |
| 7 | # Forward iterator |
| 8 | def __iter__(self): |
| 9 | n = self.start |
| 10 | while n > 0: |
| 11 | yield n |
| 12 | n -= 1 |
| 13 | |
| 14 | # Reverse iterator |
| 15 | def __reversed__(self): |
| 16 | n = 1 |
| 17 | while n <= self.start: |
| 18 | yield n |
| 19 | n += 1 |
| 20 | |
| 21 | c = Countdown(5) |
| 22 | print("Forward:") |