Dataclass: NameError: name 'WORD_TYPE' is not defined

Dataclass: NameError: name 'WORD_TYPE' is not defined

我尝试使用 SO 问题示例

@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()}'

我得到了

<ipython-input-3-df20e5b35c67> in WordItem()
      3     id: str = field(init=False)
      4     phrase: str
----> 5     word_type: WORD_TYPE
      6 
      7     def __post_init__(self):

NameError: name 'WORD_TYPE' is not defined

我的Python版本

Python 3.6.6 :: Anaconda, Inc.

WORD_TYPE 到底是什么?

你指的我相信有这个缺失,这是在class定义之前定义一个自定义类型。

from typing import NewType
WORD_TYPE = NewType('WORD_TYPE', str)

is a better example to work through for dataclasses. I would also recommend you use Python 3.7 and its native dataclasses module.