繁体   English   中英

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

[英]How to type hint that a variable should be a variable from another class?

我有以下代码,并且Book类具有type变量。 我已经添加了str作为类型提示,但是类型应该是Type类中的TYPE_ONETYPE_TWOTYPE_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM