[英]mypy doesn't warn about instantiating pure virtual class
我有一个抽象类,它指定了一个纯虚方法run
:
class Father:
def __init__(self):
self.i = 800
def run(self, s: str) -> int:
pass
class Son(Father):
def walk(self, i: int) -> int:
return self.i+i+800
s = Son()
当我运行mypy
没有发出警告,为什么?
您的示例没有抽象类或纯虚拟方法(严格来说,这不是 Python 中的东西;它只是一个抽象方法)。 它在层次结构中有两个标准类, run
函数是一个常规函数。
如果你想要一个抽象方法,你必须使用abc
模块中的位和 bob来标记它。
from abc import ABC, abstractmethod
class Father(ABC):
def __init__(self):
self.i = 800
@abstractmethod
def run(self, s: str) -> int:
...
class Son(Father):
def walk(self, i: int) -> int:
return self.i + i + 800
s = Son()
这导致
TypeError: Can't instantiate abstract class Son with abstract method run
在运行时和
error: Cannot instantiate abstract class "Son" with abstract attribute "run"
在我的时间。
如果您不关心运行时检查,请不要从ABC
派生Father
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.