为什么Mypy试图在Python中实例化我的抽象课程?
如果我有一个像这样的Python模块:
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def method(self):
pass
class ConcreteClass1(AbstractClass):
def method(self):
print("hello")
class ConcreteClass2(AbstractClass):
def method(self):
print("hello")
class ConcreteClass3(AbstractClass):
def method(self):
print("hello")
classes = [
ConcreteClass1,
ConcreteClass2,
ConcreteClass3,
]
for c in classes:
c().method()
并且我用mypy test.py
将其击中,我得到了:
test.py:27: error: Cannot instantiate abstract class "AbstractClass" with abstract attribute "method"
不过,代码在没有任何问题的情况下运行,我看不到逻辑上的任何问题。 我绝不会直接尝试实例化AbstractClass
。
我注意到的一些奇怪的行为:
如果,我这样做是这样做的:
...
ConcreteClass1().method()
ConcreteClass2().method()
ConcreteClass3().method()
Mypy很高兴。
而不是在循环中进行3堂课
classes = [
ConcreteClass1,
ConcreteClass2,
#ConcreteClass3,
]
for c in classes:
c().method()
另外,如果我做2: Mypy也对此感到满意, 。 这是怎么回事?这是一个mypy错误吗?如果是这样,我可以告诉Mypy忽略这个“问题”吗?
If I have a Python module like this:
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def method(self):
pass
class ConcreteClass1(AbstractClass):
def method(self):
print("hello")
class ConcreteClass2(AbstractClass):
def method(self):
print("hello")
class ConcreteClass3(AbstractClass):
def method(self):
print("hello")
classes = [
ConcreteClass1,
ConcreteClass2,
ConcreteClass3,
]
for c in classes:
c().method()
And I hit it with mypy test.py
, I get this:
test.py:27: error: Cannot instantiate abstract class "AbstractClass" with abstract attribute "method"
The code runs without any issues though, and I can't see any issues in the logic.
At no point am I trying to instantiate the AbstractClass
directly.
Some weird behavior I've noticed:
If, instead of a loop, I do this:
...
ConcreteClass1().method()
ConcreteClass2().method()
ConcreteClass3().method()
mypy is happy.
Also, if, instead of 3 classes in the loop, I do 2:
classes = [
ConcreteClass1,
ConcreteClass2,
#ConcreteClass3,
]
for c in classes:
c().method()
mypy is happy with that as well.
What's going on? Is this a mypy bug? If so, can I tell mypy to ignore this "problem"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该问题似乎类似于摘要类和词典的mypy问题某些原因,Mypy不能在列表上没有类型注释的情况下正确打字:(
更改
list
tolist
如果您在Python 3.8或以下)您可能想要要在Mypy Github上提出此错误的问题。
The problem appears similar to mypy issues with abstract classes and dictionaries - for some reason, mypy can't typecheck this properly without a type annotation on the list:
(Change
list
toList
if you're on Python 3.8 or below)You might want to file an issue for this bug on the mypy Github.