<pre><code>E AttributeError: __fields_set__
</code></pre>
<p>Peter T已经回答了您问题的第一部分,正如<a href="https://pydantic-docs.helpmanual.io/usage/dataclasses/" rel="nofollow noreferrer">Document</a>所说:“请记住,pydantic.dataclasses.dataclass是dataclasses.dataclass的替代品。”</p>
<p>第二部分是您希望将它们转换为dict</p>
<blockquote>
<p>The reason why I want to use pydantic is because I need a way to quickly convert Python objects to dict (or JSON) and back</p>
</blockquote>
<p>要回答这部分问题,可以使用数据类本身的<code>asdict</code><a href="https://www.python.org/dev/peps/pep-0557/#id43" rel="nofollow noreferrer">source</a></p>
<pre><code>from dataclasses import dataclass, asdict
from typing import List
@dataclass
class Point:
x: int
y: int
@dataclass
class C:
l: List[Point]
p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}
c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'l': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
</code></pre>
<p>关于这些模块级辅助函数(<code>.asdict</code>&;<code>.astuple</code>)的讨论表明它们不符合PEP8(应该是<code>as_dict()</code>和<code>as_tuple()</code>),但是最后它们决定与namedtuple保持一致。_asdict()和attr.asdict()<a href="https://www.python.org/dev/peps/pep-0557/#asdict-and-astuple-function-names" rel="nofollow noreferrer">source</a></p>