我有以下代码,Book
类有一个type
变量。我添加了str
作为类型提示,但是类型应该是TYPE_ONE
类中的TYPE_TWO
,TYPE_THREE
或Type
。
我该怎么做?
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
答案 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"))
但我现在无法考虑其他解决方案。