__init__ 的正确类型注释

问题描述 投票:0回答:2

Python 中

__init__
函数的正确类型注释是什么?

class MyClass:
    ...

以下哪项更有意义?

def __init__(self):
    # type: (None) -> None

def __init__(self):
    # type: (MyClass) -> MyClass

def __init__(self):
    # type: (None) -> MyClass

因为我们通常会实例化为

myclass = MyClass()
,但是
__init__
函数本身没有返回值。

python python-2.7 typing
2个回答
125
投票
当作为注释给出时,注释中应省略

self
,并且
__init__()
应标记为
-> None
。这一切都在 PEP-0484 中明确指定。


9
投票

如果您使用的是 Python 3(我希望您这样做),自 mypy 0.641 版本以来根本不需要注释

__init__
方法,如果至少有一个带注释的参数,它必须始终是
None
,因为它会返回没有什么。在其他情况下,mypy 会引发错误。这种行为多年来一直困扰着人们,但最终得到了解决。

这就是吉多所说的

新功能:现在允许省略

__init__
的返回类型 可以省略带注释的
__init__
方法的返回类型 没有收到错误消息。例如:

class Circuit:
    def __init__(self, voltage: float):
        self.voltage = voltage

在以前的 mypy 版本中,这会引发错误消息:

error: The return type of "__init__" must be None

这个错误很烦人,因为这是唯一合法的返回声明

__init__
是 -> None,所以我们将其删除。请注意,这仅在至少有一个带注释的参数时才有效!对于
__init__
方法,没有 您仍然必须添加参数 -> None,否则该方法将是 被视为无类型,并且其主体根本不会进行类型检查。 例子:

class UntypedExample:
    # This method is not type-checked at all!
    def __init__(self):
        self.voltage = 0.0

class TypedExample:
    # This is how to ensure that a 0-argument __init__ is type-checked:
    def __init__(self) -> None:
        self.voltage = 0.0

相关讨论:

  1. 允许
    __init__
    带签名但无返回类型
  2. 函数缺少
    __init__
    (self)
  3. 的类型注释
© www.soinside.com 2019 - 2024. All rights reserved.