+ 1

OOP python questions

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

20th Feb 2025, 2:54 PM
Sherwin
5 Respuestas
+ 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
+ 2
Sherwin You could watch YouTube channel Free Code Camp: https://youtube.com/@freecodecamp?si=6cMStHE5zjW_7EgI You can see references and tutorials in W3Schools website: https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/default.asp Also you can check Python's official documentation: https://docs.python.org/3/index.html
22nd Feb 2025, 2:57 AM
Afnan Irtesum Chowdhury
Afnan Irtesum Chowdhury - avatar
0
You guys have a high knowledge of python.can you suggest some places where I could learn these things?
22nd Feb 2025, 2:36 AM
Sherwin