【问题标题】:Python attribute type hint: list of specific strings?Python 属性类型提示:特定字符串的列表?
【发布时间】:2021-06-02 00:53:04
【问题描述】:

是否有类型提示需要字符串列表中的字符串?

import typing

@dataclass
class Person:
   name: str = None
   gender: typing.Choice(['male', 'female'])  # <- Something like this?

Person(name='John', gender='male')   # okay
Person(name='John', gender='female') # okay
Person(name='John', gender='apple')  # error

谢谢!

【问题讨论】:

标签: python type-hinting


【解决方案1】:

多个选项:

from typing import Literal
gender = Literal['male', 'female', 'other']
from enum import Enum
class Gender(Enum):
   FEMALE = "female"
   MALE = "male"
   OTHER = "other"

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 2022-07-31
    • 2020-09-02
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多