【问题标题】:dict from dataclass returns empty dictionary来自数据类的 dict 返回空字典
【发布时间】:2021-02-15 15:42:55
【问题描述】:

我是数据类的新手,我正在尝试用一种简单的方法将数据类转换为字典,然后我可以从 JSON 文件中保存和加载。在实现我的应用程序所需的基础架构之前,我正在一个小型数据类上对其进行测试,其中包含我将使用的变量,如下所示:

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())

两个打印语句都是空字典“{}”,我似乎无法弄清楚原因

【问题讨论】:

  • 你没有注释任何东西并实现了你自己的 init..

标签: python dictionary python-dataclasses


【解决方案1】:

通过覆盖__init__ 方法,您实际上使dataclass 装饰器成为空操作。我想你想要:

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())

作为输出产生:

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]}

详情请见the documentation

【讨论】:

猜你喜欢
  • 2016-03-14
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多