[英]How can I assign a one from -> Human | Animal | Alien | None as the type with @dataclass in Python 3.7.x+
[英]How can I get Python 3.7 new dataclass field types?
Python 3.7引入了稱為數據類的新功能。
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
在函數參數中使用類型提示(注釋)時,可以使用inspect模塊輕松獲取帶注釋的類型。 如何獲取dataclass字段類型?
檢查__annotations__
會為您提供原始注釋,但這些注釋不一定對應於數據類的字段類型。 像ClassVar和InitVar這樣的東西出現在__annotations__
,即使它們不是字段,並且繼承的字段也不顯示。
而是在數據dataclasses.fields
上調用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}
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)
dataclasses.py是提供裝飾器和函數的模塊,用於通過使用字段注釋生成常規類方法 。 這意味着在處理類之后,用戶定義的字段應使用PEP 526語法變量注釋形成 。 模塊注釋可以__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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.