我们为什么要在def __init__(self, n) -> None:
中使用->
?我读了下面的摘录from PEP 484,但我无法理解它的意思
(Note that the return type of
__init__
ought to be annotated with-> None
. The reason for this is subtle. If__init__
assumed a return annotation of-> None
, would that mean that an argument-less, un-annotated__init__
method should still be type-checked? Rather than leaving this ambiguous or introducing an exception to the exception, we simply say that__init__
ought to have a return annotation; the default behavior is thus the same as for other methods.)
使用def __init__(self, n) -> None:
和def __init__(self, n):
之间的细微差别是什么?有人能用简单的话解释一下引用的摘录吗
主要原因是允许静态类型检查。默认情况下,
mypy
将忽略未注释的函数和方法考虑以下定义:
mypy
是一个静态类型分析工具,默认情况下,它没有发现任何问题:但是它会生成一个运行时
TypeError
(注意python
这里是Python 3.8.6):如果添加注释
-> None
,则mypy
将键入check方法并引发错误:如果您试图通过声明
def __init__(self) -> int:
来规避检查,mypy
甚至会抱怨:还值得注意的是,任何注释都会引起
mypy
的注意;如果您至少有一个带注释的参数,则缺少返回类型与-> None
相同:将产生与显式
-> None
相同的“预期无返回值”错误。但是,显式返回类型通常比任何人工参数类型提示更容易提供,并且可以说比尝试键入self
更清晰这只有在您关心类型注释时才重要,如果不关心,则可以跳过。它不会在运行时更改功能(除了在private
__annotations__
属性中添加信息)那么它做什么呢?
->
用于记录函数返回的数据类型。然后,类型在后面,在您的例子中,类型是
None
所以它说这个方法不返回任何东西,或者如果它确实返回了一些东西,它总是
None
如果要返回某个内容,则将其更改为返回集的类型
在python 3.5中出现了类型注释选项
def __init__(self, n) -> None:
意味着__init__
应该始终返回NoneType,如果您意外地返回与None不同的内容,尤其是如果您使用mypy或其他类似的内容,那么它会非常有用。但是如果你喜欢用老办法,你可以忽略它相关问题 更多 >
编程相关推荐