Python 3.7 引入了一个名为数据类(data classes)的新特性。
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
在函数参数中使用类型提示(注释)时,您可以使用inspect模块轻松获取注释的类型。如何获取dataclass字段的类型?
Python 3.7 引入了一个名为数据类(data classes)的新特性。
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
在函数参数中使用类型提示(注释)时,您可以使用inspect模块轻松获取注释的类型。如何获取dataclass字段的类型?
__annotations__
可以获得原始注释,但这些注释不一定对应于数据类的字段类型。像ClassVar和InitVar这样的东西出现在__annotations__
中,即使它们不是字段,继承的字段也不会显示出来。dataclasses.fields
来获取数据类上的字段对象并进行检查。field_types = {field.name: field.type for field in fields(MyClass)}
__annotations__
和fields
都不能解析字符串注释。如果你想解析字符串注释,最好的方法可能是使用typing.get_type_hints
。get_type_hints
将包括ClassVars和InitVars,所以我们使用fields
来过滤它们:
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}
__annotations__
无法解析父类中的字段。 - ollik1field.default
(如果没有默认值,则为dataclasses.MISSING
)。 - user2357112from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
myclass = MyClass()
myclass.__annotations__
>> {'id': int, 'name': str}
myclass.__dataclass_fields__
>> {'id': Field(name='id',type=<class 'int'>,default=0,default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
'name': Field(name='name',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)}
另外一方面需要注意的是:
myclass.__dataclass_params__
>>_DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
from __future__ import annotations
语句,则type
字段将是类型的字符串表示而不是类型本身。请注意不要改变原始含义,并使翻译更通俗易懂。 - Wolfgang Pfnür__annotations__
属性访问。__annotations__
属性或使用typing.get_type_hints来访问已注释的类型,建议使用后者。from typing import Dict, ClassVar, get_type_hints
from dataclasses import dataclass
@dataclass
class Starship:
hitpoints: int = 50
get_type_hints(Starship) // {'hitpoints': int}
Starship.__annotations__ // {'hitpoints': int}
dataclasses.__annotations__ // The annotations of the dataclasses module.
get_type_hints(get_type_hints)
__annotations__
。 - Andriy Ivaneyko