为什么我们要在def_uuuinit_uuu(self,n)>None:中使用>呢?

2024-09-30 08:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我们为什么要在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):之间的细微差别是什么?有人能用简单的话解释一下引用的摘录吗


Tags: ofthetoselfnoneforreturnthat
3条回答

主要原因是允许静态类型检查。默认情况下,mypy将忽略未注释的函数和方法

考虑以下定义:

class Foo:
    def __init__(self):
        return 3

f = Foo()

mypy是一个静态类型分析工具,默认情况下,它没有发现任何问题:

$ mypy tmp.py
Success: no issues found in 1 source file

但是它会生成一个运行时TypeError(注意python这里是Python 3.8.6):

$ python tmp.py
Traceback (most recent call last):
  File "tmp.py", line 5, in <module>
    f = Foo()
TypeError: __init__() should return None, not 'int'

如果添加注释-> None,则mypy将键入check方法并引发错误:

$ mypy tmp.py
tmp.py:3: error: No return value expected
Found 1 error in 1 file (checked 1 source file)

如果您试图通过声明def __init__(self) -> int:来规避检查,mypy甚至会抱怨:

$ mypy tmp.py
tmp.py:2: error: The return type of "__init__" must be None
Found 1 error in 1 file (checked 1 source file)

还值得注意的是,任何注释都会引起mypy的注意;如果您至少有一个带注释的参数,则缺少返回类型与-> None相同:

def __init__(self, x: int):
     return x

将产生与显式-> None相同的“预期无返回值”错误。但是,显式返回类型通常比任何人工参数类型提示更容易提供,并且可以说比尝试键入self更清晰

这只有在您关心类型注释时才重要,如果不关心,则可以跳过。它不会在运行时更改功能(除了在private__annotations__属性中添加信息)

那么它做什么呢?
->用于记录函数返回的数据类型。
然后,类型在后面,在您的例子中,类型是None

所以它说这个方法不返回任何东西,或者如果它确实返回了一些东西,它总是None

如果要返回某个内容,则将其更改为返回集的类型

在python 3.5中出现了类型注释选项def __init__(self, n) -> None:意味着__init__应该始终返回NoneType,如果您意外地返回与None不同的内容,尤其是如果您使用mypy或其他类似的内容,那么它会非常有用。但是如果你喜欢用老办法,你可以忽略它

相关问题 更多 >

    热门问题