[英]How to type hint that a variable should be a variable from another class?
我有以下代码,并且Book
类具有type
变量。 我已经添加了str
作为类型提示,但是类型应该是Type
类中的TYPE_ONE
, TYPE_TWO
或TYPE_THREE
。
我怎样才能做到这一点?
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
您应该改为使用枚举:
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"))
但我现在无法考虑其他解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.