如何键入提示变量应该是另一个类的变量?

时间:2019-08-02 08:02:29

标签: python python-3.x

我有以下代码,Book类有一个type变量。我添加了str作为类型提示,但是类型应该是TYPE_ONE类中的TYPE_TWOTYPE_THREEType

我该怎么做?

class Type:
    TYPE_ONE = 'one'
    TYPE_TWO = 'two'
    TYPE_THREE = 'three'


@dataclass(frozen=True)
class Book:
    title: str
    description: str
    type: str  # type should be one attribute of the `Type` class

1 个答案:

答案 0 :(得分:4)

您应该改为使用枚举:

from enum import Enum

class Type(Enum):
    TYPE_ONE = 'one'
    TYPE_TWO = 'two'
    TYPE_THREE = 'three'


@dataclass(frozen=True)
class Book:
    title: str
    description: str
    type: Type

参考:https://docs.python.org/3/library/enum.html

编辑:

我不考虑枚举的另一种解决方案是使用NewType

from typing import NewType

TypeAttr = NewType("TypeAttr", str)


class Type:
    TYPE_ONE: TypeAttr = TypeAttr('one')
    TYPE_TWO: TypeAttr = TypeAttr('two')
    TYPE_THREE: TypeAttr = TypeAttr('three')


@dataclass(frozen=True)
class Book:
    title: str
    description: str
    type: TypeAttr

参考:https://docs.python.org/3/library/typing.html#newtype

不幸的是,这样做很容易将其破坏:

b = Book("title", "description", TypeAttr("not Type attribute"))

但我现在无法考虑其他解决方案。