Python3.7 的dataclass新特性大大简化了定义类对象的代码量,代码简洁明晰。通过使用 @dataclass 装饰器来修饰类,本文主要介绍获取dataclass类中字段类型(Field)的方法。

1、使用.__annotations__和__dataclass_fields__

from dataclasses import dataclass

@dataclass
class MyClass:
    id: int = 0
    name: str = '' 

myclass = MyClass()

print(myclass.__annotations__)
print(myclass.__dataclass_fields__)

2、使用dataclasses.fields

文档:

dataclasses.fields

typing.get_type_hints

from dataclasses import dataclass
from dataclasses import fields
import typing

@dataclass
class MyClass:
    id: int = 0
    name: str = '' 
field_types = {field.name: field.type for field in fields(MyClass)}
print(field_types)
#或者
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}
print(resolved_field_types)