为什么 mypy 试图在 Python 中实例化我的抽象类?

社会演员多 python 182

原文标题Why is mypy trying to instantiate my abstract class in 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 个类,而是执行 2 个:

classes = [
    ConcreteClass1,
    ConcreteClass2,
    #ConcreteClass3,
]

for c in classes:
    c().method()

mypy 对此也很满意。这是怎么回事?这是一个mypy错误吗?如果是这样,我可以告诉 mypy 忽略这个“问题”吗?

原文链接:https://stackoverflow.com//questions/71918897/why-is-mypy-trying-to-instantiate-my-abstract-class-in-python

回复

我来回复
  • SuperStormer的头像
    SuperStormer 评论

    这个问题看起来与抽象类和字典的 tomypy 问题类似——由于某种原因,如果没有列表上的类型注释,mypy 无法正确地对它进行类型检查:

    classes: list[Type[AbstractClass]] = [
        ConcreteClass1,
        ConcreteClass2,
        ConcreteClass3,
    ]
    

    您可能想在 mypy Github 上针对此错误提交问题。

    2年前 0条评论