繁体   English   中英

类型提示适合函数参数,但不适合返回类型

[英]type hinting pitches a fit about function arguments but not the return type

我对 Python 相当陌生,很高兴发现 Python3 中的类型提示功能。 我通读了PEP 484在 SO 上发现了这个问题,其中提出问题的人想知道为什么没有检查函数的返回类型。 受访者指出 PEP 484 中的一个部分指出检查不会在运行时发生,其意图是类型提示将由外部程序解析。

我启动了 python3 REPL 并决定尝试一下

>>> def greeting() -> str: return 1
>>> greeting()
1

到现在为止还挺好。 我对函数参数很好奇所以我尝试了这个:

>>> def greeting2(name: str) -> str: return 'hi ' + name
>>> greeting2(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in greeting2
TypeError: Can't convert 'int' object to str implicitly

现在这是轮子似乎脱落的地方,因为它似乎,至少在功能参数方面,有检查。 我的问题是为什么检查参数而不检查返回类型?

Python 在运行时不使用类型提示(不适用于函数参数和返回类型)。 它与以下没有什么不同:

>>> def greeting3(name): return 'hi ' + name
...
>>> greeting3(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in greeting3
TypeError: Can't convert 'int' object to str implicitly

你得到那个 TypeError 因为你试图连接一个字符串和一个整数:

>>> 'hi ' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

如前所述,类型提示不会在运行时检查,它们旨在由您的编辑器/工具在开发期间使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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