擅长:python、mysql、java
<p>检查<code>__annotations__</code>会提供原始注释,但这些注释不一定对应于数据类的字段类型。像ClassVar和InitVar这样的东西出现在<code>__annotations__</code>中,即使它们不是字段,继承的字段也不会出现。</p>
<p>相反,对数据类调用<a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.fields" rel="noreferrer">^{<cd3>}</a>,并检查字段对象:</p>
<pre><code>field_types = {field.name: field.type for field in fields(MyClass)}
</code></pre>
<hr/>
<p><code>__annotations__</code>和<code>fields</code>都不会解析字符串注释。如果要解析字符串注释,最好的方法可能是<a href="https://docs.python.org/3/library/typing.html#typing.get_type_hints" rel="noreferrer">^{<cd6>}</a>。<code>get_type_hints</code>将包括ClassVars和InitVars,因此我们使用<code>fields</code>来过滤它们:</p>
<pre><code>resolved_hints = typing.get_type_hints(MyClass)
field_names = [field.name for field in fields(MyClass)]
resolved_field_types = {name: resolved_hints[name] for name in field_names}
</code></pre>