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 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
这个错误很烦人,因为这是唯一合法的返回声明
是 -> None,所以我们将其删除。请注意,这仅在至少有一个带注释的参数时才有效!对于__init__
方法,没有 您仍然必须添加参数 -> None,否则该方法将是 被视为无类型,并且其主体根本不会进行类型检查。 例子:__init__
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
相关讨论: