Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类型暗示对函数参数而不是返回类型进行匹配_Python_Python 3.5_Type Hinting - Fatal编程技术网

Python 类型暗示对函数参数而不是返回类型进行匹配

Python 类型暗示对函数参数而不是返回类型进行匹配,python,python-3.5,type-hinting,Python,Python 3.5,Type Hinting,我是Python的新手,很高兴在Python3中发现了类型暗示功能。我通读了一遍,发现问问题的人想知道为什么没有检查函数的返回类型。回答者指出PEP 484中的一节,该节说明检查不会在运行时发生,其目的是由外部程序解析类型提示 我启动了python3repl并决定尝试一下 >>> def greeting() -> str: return 1 >>> greeting() 1 到目前为止还不错。我对函数参数很好奇,所以我尝试了以下方法: >>

我是Python的新手,很高兴在Python3中发现了类型暗示功能。我通读了一遍,发现问问题的人想知道为什么没有检查函数的返回类型。回答者指出PEP 484中的一节,该节说明检查不会在运行时发生,其目的是由外部程序解析类型提示

我启动了python3repl并决定尝试一下

>>> 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
def问候2(名称:str)->str:返回'hi'+名称 >>>欢迎2(2) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“”,第1行,在问候语2中 TypeError:无法将“int”对象隐式转换为str
现在这是车轮脱落的地方,因为至少在功能参数方面,似乎有检查。我的问题是为什么要检查参数而不是返回类型

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
def问候3(名称):返回'hi'+名称 ... >>>欢迎3(2) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“”,第1行,在问候语3中 TypeError:无法将“int”对象隐式转换为str 您得到该类型错误是因为您试图连接字符串和整数:

>>> 'hi ' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>“嗨”+2
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无法将“int”对象隐式转换为str

如前所述,在运行时不会检查类型提示,它们是供编辑器/工具在开发过程中使用的。

这不是类型检查,如果没有类型提示,您将出现此错误。Python是一种强类型语言。它不检查函数参数的类型,因为它允许您使用整数而不是字符串调用
greeting2
。ahhh。好吧,那就更有意义了。我应该更注意错误的文本。快速响应的t/y!