如何使用数据类生成字段值? [英] How to use dataclasses to generate a field value?
本文介绍了如何使用数据类生成字段值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
class WordItem:
def __init__(self, phrase: str, word_type: WORD_TYPE):
self.id = f'{phrase}_{word_type.name.lower()}'
self.phrase = phrase
self.word_type = word_type
@classmethod
def from_payload(cls, payload: Dict[str, Any]) -> 'WordItem':
return cls(**payload)
如何将此类重写为数据类?
具体地说,应该如何声明id
字段?它具有一个生成的值,而不是创建实例的代码所提供的字段.
Specifically, how should the id
field be declared? It has a generated value, and is not a field that the code creating instances would provide.
推荐答案
Just move each of your attributes to a type-annotated declaration on the class, where the class has been decorated with the @dataclasses.dataclass
decorator.
您可以在 __post_init__
方法;确保使用
from dataclasses import dataclass, field
@dataclass
class WordItem:
id: str = field(init=False)
phrase: str
word_type: WORD_TYPE
def __post_init__(self):
self.id = f'{self.phrase}_{self.word_type.name.lower()}'
演示:
>>> from types import SimpleNamespace
>>> wt = SimpleNamespace(name='Python')
>>> WordItem('await', wt)
WordItem(id='await_python', phrase='await', word_type=namespace(name='Python'))
这篇关于如何使用数据类生成字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文