__init__的正确类型注释

use*_*531 11 python typing python-2.7

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

class MyClass:
    ...
Run Code Online (Sandbox Code Playgroud)

以下哪项更有意义?

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

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

def __init__(self):
    # type: (None) -> MyClass
Run Code Online (Sandbox Code Playgroud)

因为我们通常会实例化为myclass = MyClass(),但__init__函数本身没有返回值.

rem*_*ram 18

self当注释作为注释给出时,应该从注释中省略,并且__init__()应该标记为-> None.这都是在PEP-0484中明确指定的.

  • PEP 484 说 *return type* 应该被注释为 `-> None`,而不是应该省略 `self`。 (6认同)
  • 你能否澄清一下“`self`应该被省略。” 您实际上不是要省略“self”参数,而是要省略“self”的类型提示? (4认同)
  • 实际上,该规则没有明确说明.但是[这里](https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)省略了`self`的例子. (3认同)
  • 这些示例显示了 Python 3 代码在方法签名中使用 `self` 和 `-> None` 作为返回类型,这是你应该做的。如果您想要 Python 2 兼容性,您可以将类型签名放入注释中,在这种情况下,您可以在注释类型签名中省略“self”。你当然不会在方法参数中遗漏`self`,否则你会得到参数计数不匹配的错误,因为第一个参数将取代self。无论你给它贴上什么标签都没有关系,按照惯例,它只是“自我”。你可能是这个意思,但不清楚。 (2认同)
  • 顺便说一句,“mypy”允许从“__init__”中省略“-> None”——尽管经过了深入讨论——因为“__init__”只能具有此返回类型(对于类型检查,“-> None”会自动追加) ,请参阅 https://github.com/python/mypy/issues/604 (2认同)

fun*_*man 8

如果您使用的是 Python 3(我希望您这样做),则自 mypy 0.641 发布以来根本不需要注释__init__方法,如果至少有一个带注释的参数,则它必须始终是None,因为它什么也不返回。在其他情况下,mypy 会引发错误。这种行为多年来一直困扰着人们,但最终得到了解决。

\n

吉多是这样说的

\n
\n

新功能:允许省略返回类型现在__init__\n可以省略带注释的方法的返回类型__init__\n而不会收到错误消息。例如:

\n
class Circuit:\n    def __init__(self, voltage: float):\n        self.voltage = voltage\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
error: The return type of "__init__" must be None\n
Run Code Online (Sandbox Code Playgroud)\n

这个错误很烦人,因为 \n 唯一合法的返回声明__init__是 -> None,所以我们 \xe2\x80\x99 删除了它。请注意,这仅在存在\xe2\x80\x99s 至少一个带注释的参数时才有效!对于__init__没有\n参数的方法,您仍必须添加 -> None,否则该方法\n将被视为无类型,并且根本不会对其主体进行类型检查。\n示例:

\n
class UntypedExample:\n    # This method is not type-checked at all!\n    def __init__(self):\n        self.voltage = 0.0\n\nclass TypedExample:\n    # This is how to ensure that a 0-argument __init__ is type-checked:\n    def __init__(self) -> None:\n        self.voltage = 0.0\n
Run Code Online (Sandbox Code Playgroud)\n
\n

相关讨论:

\n
    \n
  1. 允许__init__带签名但不带返回类型
  2. \n
  3. 函数缺少__init__(self)的类型注释
  4. \n
\n