Last active
November 4, 2020 06:48
-
-
Save whal-e3/1b36e09a4d3572a44c2cfb54ec71acb0 to your computer and use it in GitHub Desktop.
Python OOP User defined iterator ( how to use __iter__ and __next__ )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class EvenNum: | |
| def __init__(self, size) -> None: | |
| self.size = size | |
| print(self, end=" : ") | |
| def __iter__(self): | |
| self.count = 0 | |
| return self | |
| def __next__(self): | |
| self.count += 1 | |
| if self.count > self.size: | |
| raise StopIteration | |
| return 2 * self.count | |
| test = EvenNum(5) | |
| even = iter(test) | |
| print(next(even), end=" ") | |
| print(next(even), end=" ") | |
| print(next(even), end=" ") | |
| print(next(even), end=" ") | |
| print(next(even), end=" ") | |
| print(next(even), end=" ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment