我正在使用新的Python 3.5模块输入,它很高兴.
我想知道如何根据精确的字符串文字指定类型.例如,函数保证返回四个字符串中的一个 - "North","West","East","South" - 我们如何将其表示为特定类型变量,而不仅仅是str.
我查看了文档,找到了Union类型和TypeVar功能,但无法找到答案.
表达此问题的示例函数:
def compute_quadrant(x: int, y: int) -> str:
if x > 0 and y > 0:
return 'I'
elif x < 0 and y > 0:
return 'II'
elif x < 0 and y < 0:
return 'III'
elif x > 0 and y < 0:
return 'IV'
Run Code Online (Sandbox Code Playgroud)
而不是仅仅恢复str,我想回到一个更具体的类型,它是四个值之一- ,"I","II","III"或"IV".
在Typescript中,人们可以做到:type Quadrant = …