Skip to content

Instantly share code, notes, and snippets.

@ehzawad
Last active February 28, 2023 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehzawad/271092f4b6f044363c499612a938095e to your computer and use it in GitHub Desktop.
Save ehzawad/271092f4b6f044363c499612a938095e to your computer and use it in GitHub Desktop.
Python iiterable
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
city: str
def __iter__(self):
self._fields = [field.name for field in self.__dataclass_fields__.values()]
self._index = 0
return self
def __next__(self):
if self._index == len(self._fields):
raise StopIteration
field = self._fields[self._index]
value = getattr(self, field)
self._index += 1
return value
person = Person("John", 25, "New York")
for prop in person:
print(prop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment