擅长:python、mysql、java
<p>数据类更像<code>namedtuple</code>和流行的<a href="http://www.attrs.org" rel="noreferrer">attrs</a>包,而不是<code>SimpleNamespace</code>(在<a href="https://www.python.org/dev/peps/pep-0557/" rel="noreferrer">the PEP</a>中甚至没有提到)。它们有两个不同的目的。在</p>
<p><strong>数据类</strong></p>
<ul>
<li>结构化</li>
<li>类型化(默认情况下,但可选)</li>
<li>编写基本dunder方法的大部分样板文件(<code>__init__</code>,<code>__hash__</code>,<code>__eq__</code>,等等)</li>
<li>为属性的默认值提供简单的机制</li>
<li>可以轻松添加<code>__slots__</code>和方法</li>
</ul>
<p><strong>SimpleNamespace</strong></p>
<ul>
<li>“抓包”数据结构</li>
<li>当你需要一本字典而不是一个类时使用</li>
<li>不打算使用<code>__slots__</code></li>
</ul>
<p>来自<code>SimpleNamespace</code>文档:</p>
^{bq}$
<p>由于<code>@dataclass</code>应该替换<code>namedtuple</code>的许多用例,命名记录/结构应该用<code>@dataclass</code>完成,而不是<code>SimpleNamespace</code>。在</p>
<p>您可能还想看看<a href="https://pyvideo.org/pycon-us-2018/dataclasses-the-code-generator-to-end-all-code-generators.html" rel="noreferrer">this PyCon talk by Raymond Hettinger</a>,在这里他进入了<code>@dataclass</code>的背景知识和它的用法。在</p>