+ 1

OOP python questions

Is a class iterable in python (can we iterate through a class)?

20th Feb 2025, 2:54 PM
Sherwin
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)
20th Feb 2025, 3:07 PM
Afnan Irtesum Chowdhury
Afnan Irtesum Chowdhury - avatar
+ 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
21st Feb 2025, 3:22 AM
Bob_Li
Bob_Li - avatar
+ 3
Use a metaclass as a constructor for your class to get the desired iterable behavior. https://sololearn.com/compiler-playground/cOAQcq5yLd2P/?ref=app
21st Feb 2025, 11:09 AM
Vitaly Sokol
Vitaly Sokol - avatar