Python iiterable
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
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