[英]dataclasses.asdict() not working as expected
I'm using dataclass
and asdict
from dataclasses
, and I find that asdict
doesn't work as I would expect when I introduce inheritance. 我使用的
dataclass
和asdict
从dataclasses
,我发现asdict
不工作,当我介绍继承我期望的那样。
I use dataclasses
to help me create dictionaries from classes so I can pass them into django.shortcuts.render
. 我使用
dataclasses
来帮助我从类中创建字典,以便将它们传递给django.shortcuts.render
。
from dataclasses import dataclass
from dataclasses import asdict
@dataclass
class Base:
name: str
class Test(Base):
def __init__(self, age, *args, **kwargs):
self.age = age
super(Test, self).__init__(*args, **kwargs)
test = Test(age=20, name="john doe")
print(asdict(test))
I would expect the output to be 我希望输出是
{"age": 20, "name": "john doe"}
But what I get is only the keyword-value from the base-class 但是我得到的只是基类的关键字值
{"name": "john doe"}
The correct implementation for inheritance of a dataclass
is covered in the docs : docs涵盖了
dataclass
继承的正确实现:
@dataclass
class Base:
name: str
@dataclass
class Child(Base):
age: int
Without this, the __dataclass_fields__
attribute in the child class, which asdict
uses to determine what should be in the dictionary, doesn't know about all of the fields you care about; 没有这个,子类中的
__dataclass_fields__
属性将被asdict
用来确定字典中应该包含的内容,而不知道您关心的所有字段。 it only has the inherited version: 它只有继承的版本:
>>> Test.__dataclass_fields__
{'name': Field(...)}
>>> Test.__dataclass_fields__ is Base.__dataclass_fields__
True
>>> Child.__dataclass_fields__
{'name': Field(...), 'age': Field(...)}
>>> Child.__dataclass_fields__ is Base.__dataclass_fields__
False
Also note you can simplify the imports to: 另请注意,您可以将导入简化为:
from dataclasses import asdict, dataclass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.