JPF*_*oia 7 python annotations
既然python 3.6(或3.4?我不记得了)我们可以注释一个函数.例如:
def getVersion() -> str:
Run Code Online (Sandbox Code Playgroud)
现在当函数返回一个元组时会发生什么?我们能做到这一点:
def func() -> tuple:
Run Code Online (Sandbox Code Playgroud)
但是,如果我们知道元组是两个整数的元组?我在这里阅读:如何注释多个返回值的类型?我们可以这样做:
def func() -> Tuple[int, int]
Run Code Online (Sandbox Code Playgroud)
但它需要导入typing模块.
我也试过了:
def func() -> (int, int):
Run Code Online (Sandbox Code Playgroud)
它不会崩溃.
什么是正确的方法?
注释可用于您喜欢的任何内容:它们是任意的 Python 表达式(不过,正在讨论在未来的 Python 版本中打破这一点)。
这就是为什么(int, int)用作注释的原因。 (1 + 3)也可用作注释。
一些注解被mypy其他 Python 类型检查器理解为类型注解:Tuple[Int, Int]就是这样的注解。
简而言之:使用Tuple[int, int].
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |