Reputation: 315
I'm new to dataclasses and am trying to make a simple way to convert one to a dictionary with I can then save and load from a JSON file. Before I implement the infrastructure I need for my application, I'm testing it on a small dataclass with the variables I'll be working with which is below:
from dataclasses import dataclass, asdict
@dataclass
class TestClass:
def __init__(self, floatA:[float], intA:[int], floatB:[float]):
self.var1 = floatA
self.var2 = intA
self.var3 = floatB
def ConvertToDict(self):
return asdict(self)
test = TestClass([0.2,0.1,0.5], [1,2,3], [0.9,0.7,0.6])
print(asdict(test))
print(test.ConvertToDict())
Both print statements are an empty dictionary '{}' and I can't seem to figure out why
Upvotes: 3
Views: 4082
Reputation: 311516
By overriding the __init__
method you are effectively making the dataclass
decorator a no-op. I think you want:
from dataclasses import dataclass, asdict
@dataclass
class TestClass:
floatA: float
intA: int
floatB: float
def asdict(self):
return asdict(self)
test = TestClass([0.2,0.1,0.5], [1,2,3], [0.9,0.7,0.6])
print(test)
print(test.asdict())
Which produces as output:
TestClass(floatA=[0.2, 0.1, 0.5], intA=[1, 2, 3], floatB=[0.9, 0.7, 0.6])
{'floatA': [0.2, 0.1, 0.5], 'intA': [1, 2, 3], 'floatB': [0.9, 0.7, 0.6]}
See the documentation for details.
Upvotes: 8