3 Antworten
+ 11
A class isn't iterable by default, but you can make instances of it iterable. This is done by using the special methods like __iter__() and __next__(). Example:
class iterableClass:
def __init__(self, string):
self.string = string
self.index = 0
def __iter__(self):
return self # Returns itself, basically iterating itself
def __next__(self):
if self.index >= len(self.string):
raise StopIteration
letter = self.string[self.index]
self.index += 1
return letter
# Sample usage
myString = iterableClass("Iterating Class")
for letter in myString:
print(letter)
+ 6
interesting.
It got me thinking on how it's useful...
Instead of defining an __iter__ method, I instead subclassed one class to collections.UserList. Then it became basically a custom list class.
how about a list where you can only append?
https://sololearn.com/compiler-playground/cHUw53g69OZf/?ref=app
+ 3
Use a metaclass as a constructor for your class to get the desired iterable behavior.
https://sololearn.com/compiler-playground/cOAQcq5yLd2P/?ref=app