是什么让pylint认为我的类是抽象的?

5 投票
2 回答
4028 浏览
提问于 2025-04-15 17:29

根据我的理解,Python(2.5.2)并不真正支持抽象类。为什么pylint会抱怨这个类是“未引用的抽象类”?如果一个类抛出了NotImplementedError,它会对所有这样的类都这样吗?

我把每个类都放在自己的文件里,所以如果真是这样,我想我只能压制这个消息,但我希望可能有其他解决办法。

"""Package Repository interface."""


class PackageRepository(object):
    """Package Repository interface."""

    def __init__(self):
        self.hello = "world"

    def get_package(self, package_id):
        """
        Get a package by ID.
        """
        raise NotImplementedError( \
                "get_package() method has not been implemented")

    def get_packages(self):
        """
        Get all packages.
        """
        raise NotImplementedError( \
                "get_packages() method has not been implemented")

    def commit(self):
        """
        Commit all changes.
        """
        raise NotImplementedError( \
                "commit() method has not been implemented")

    def do_something(self):
        """
        Doing something.
        """
        return self.hello

编辑

也许我应该澄清一下。我知道这是一个抽象类,我很想使用抽象关键字,但据我所知,在Python中(至少在我现在使用的版本中)这些都不重要,所以我没有去做那些复杂的抽象操作(就像这里提到的),就直接省略了。

我很惊讶pylint能自己识别出这是一个抽象类。pylint是怎么判断这是一个抽象类的?它只是简单地查找某个地方抛出的NotImplementedError吗?

2 个回答

1

根据我的经验,pylint 有点过于严格,直到你关闭了一些警告,它才会变得有用。

12

顺便提一下,抛出 NotImplementedError 就足够让 pylint 认为这是一个抽象类(这完全正确)。来自 logilab.org/card/pylintfeatures: W0223: 方法 %r 在类 %r 中是抽象的,但没有被重写。当一个抽象方法(也就是抛出 NotImplementedError 的方法)没有在具体类中被重写时,就会出现这个警告。– Tobiesque 2小时前

撰写回答