简体   繁体   English

如何覆盖 Python Dataclass 'asdict' 方法

[英]How to overwrite Python Dataclass 'asdict' method

I have a dataclass, which looks like this:我有一个数据类,它看起来像这样:

@dataclass
class myClass:
   id: str
   mode: str
   value: float

This results in:这导致:

dataclasses.asdict(myClass)
{"id": id, "mode": mode, "value": value}

But what I want is但我想要的是

{id:{"mode": mode, "value": value}}

I thought I could achive this by adding a to_dict method to my dataclass, which returns the desired dict, but that didn't work.我以为我可以通过向我的数据类添加一个to_dict方法来实现这一点,该方法返回所需的字典,但这不起作用。

How could I get my desired result?我怎样才能得到我想要的结果?

from dataclasses import dataclass, asdict


@dataclass
class myClass:
    id: str
    mode: str
    value: float


def my_dict(data):
    return {
        data[0][1]: {
            field: value for field, value in data[1:]
        }
    }


instance = myClass("123", "read", 1.23)

data = {"123": {"mode": "read", "value":  1.23}}

assert asdict(instance, dict_factory=my_dict) == data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM