如何获得Python 3.7的新数据类字段类型? [英] How can I get Python 3.7 new dataclass field types?

查看:93
本文介绍了如何获得Python 3.7的新数据类字段类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.7引入了称为数据类的新功能.

Python 3.7 introduces new feature called data classes.

from dataclasses import dataclass

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

在函数参数中使用类型提示(注释)时,可以使用inspect模块轻松获得带注释的类型.如何获取数据类字段类型?

When using type hints (annotation) in function parameters, you can easily get annotated types using inspect module. How can I get dataclass field types?

推荐答案

from 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)

这篇关于如何获得Python 3.7的新数据类字段类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆