Last active
June 14, 2021 02:28
-
-
Save ivanleoncz/2506480daf6e4b78fca25ca7a0af8e08 to your computer and use it in GitHub Desktop.
Custom iterator object examples.
This file contains 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 MyIterator: | |
def __init__(self, limit): | |
self.limit = limit | |
def __iter__(self): | |
self.a = 1 | |
return self | |
def __next__(self): | |
if self.a <= self.limit: | |
x = self.a | |
self.a += 1 | |
return x | |
else: | |
raise StopIteration | |
obj = MyIterator(10) | |
my_iter = iter(obj) | |
for x in my_iter: | |
print(f"Step: {x}") |
This file contains 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 MyIterator: | |
def __iter__(self): | |
self.a = 1 | |
return self | |
def __next__(self): | |
x = self.a | |
self.a += 1 | |
return x | |
obj = MyIterator() | |
my_iter = iter(obj) | |
print(next(my_iter)) | |
print(next(my_iter)) | |
print(next(my_iter)) | |
print(next(my_iter)) | |
print(next(my_iter)) |
This file contains 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 MyIterator: | |
def __iter__(self): | |
self.a = 1 | |
return self | |
def __next__(self): | |
x = self.a | |
self.a += 1 | |
return x | |
obj = MyIterator() | |
my_iter = iter(obj) | |
for i in my_iter: | |
print(i) | |
if i == 10: | |
print("This iteration will go forever if we don't stop it...") | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment