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
文档:
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)