Kir*_*ill 16 python type-hinting python-3.x
当我为返回一个参数的函数编写注释时,我没有任何问题。
def func() -> str:
return "ok"
Run Code Online (Sandbox Code Playgroud)
但是,当我编写带有两个或多个参数的注释时,我的PyCharm给了我SyntaxError: invalid syntax。
def func() -> str, str:
return "ok - 1", "ok - 2"
Run Code Online (Sandbox Code Playgroud)
我认为参数可以与组合使用tuple,但是我认为这不是最好的方法。
我的问题是:如何正确注释带有两个或多个返回参数的函数?
gmd*_*mds 24
用途typing.Tuple:
from typing import Tuple
def func() -> Tuple[str, str]:
return 'a', 'b'
Run Code Online (Sandbox Code Playgroud)
这是适当的,因为从概念上讲,您实际上是在返回tuple包含这些值的单个。注意:
print(type(func()))
Run Code Online (Sandbox Code Playgroud)
输出:
<class 'tuple'>
Run Code Online (Sandbox Code Playgroud)
除了空tuple(()),括号是不必要定义tuple,即该装置'a', 'b'被作为一个创建tuple,而不是被各自的值由聚集成一个return语句。
| 归档时间: |
|
| 查看次数: |
1048 次 |
| 最近记录: |