Is it possible to iterate over attributes of a instance of dataclass in python? For example, I would like in the __post_init__
double the integer attributes:
from dataclasses import dataclass, fields
@dataclass
class Foo:
a: int
b: int
def __post_init__(self):
self.double_attributes()
def double_attributes(self):
for field in fields(Foo):
field = field*2
x = {
'a': 1,
'b': 2
}
y = Foo(**x)
>>> TypeError: unsupported operand type(s) for *: 'Field' and 'int'
How to access value of instances of a class and set it to something else like below but in a loop?
@dataclass
class Foo:
a: int
b: int
def __post_init__(self):
self.double_a()
self.double_b()
def double_a(self):
self.a = self.a*2
def double_b(self):
self.b = self.b*2