python - pylint 和 abc - 抽象方法

标签 python pylint abc

import abc


class Human(object):
    __metaclass__ = abc.ABCMeta

    config = {
        'num_ears': 2,
        'num_hands': 2,
    }

    def __init__(self):
        self.config = dict(self.config.items() + self.derived_config.items())

    @abc.abstractproperty
    def derived_config(self):
        pass

    # logic that does stuff with self.config


class Clown(Human):

    derived_config = {
        'funny': True,
        'smile': True,
    }

    def __init__(self, *args, **kwargs):
        self.derived_config = dict(self.derived_config.items() + self.implementation_config.items())

        super(Clown, self).__init__(*args, **kwargs)

    @abc.abstractproperty
    def implementation_config(self):
        pass

    # logic that does stuff with self.config


class OneHandedClown(Clown):

    implementation_config = {
        'smile': False,
        'num_jokes': 20,
        'num_hands': 1,
    }


if __name__ == '__main__':
    s = OneHandedClown()
    print s.config     # {'funny': True, 'num_hands': 1, 'num_jokes': 20, 'num_ears': 2, 'smile': False}

我想明确指出 derived_config 属性对于 Human 的派生类是必需的,抽象属性装饰器起到了作用,从某种意义上说,派生类不需要的代码设置此属性将不会运行。

但是 pylint 失败并出现以下错误:

W: 39, 0: Method 'derived_config' is abstract in class 'Human' but is not overridden (abstract-method)

注意:

  • pylint 不会提示抽象属性 implementation_config,但模式是相同的(除了 OneHandedClown 是终端叶) .
  • 如果我在 OneHandedClown 中删除类变量 implementation_config,
  • pylint 提示

如何在不使用 pylint-disable 的情况下确保 lint 通过,同时使用抽象属性来确保继承契约是显式的?

最佳答案

我找到了解决方案,但没有答案。

...


class Clown(Human):

    clown_config = {
        'funny': True,
        'smile': True,
    }

    @property
    def derived_config(self):
        return dict(self.clown_config.items() + self.implementation_config.items())


    @abc.abstractproperty
    def implementation_config(self):
        pass

    # logic that does stuff with self.config


...

特别是,为什么设置类变量implementation_config足以实现Clown中的抽象属性,但是之前derived_config的实现Clown 还不足以在 Human 中实现相应的抽象属性吗?

关于python - pylint 和 abc - 抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345113/

相关文章:

python - Python 中频率权重的排名相关性

python - 从 Latex 代码文件中提取所有 Latex 命令

Python 抽象基类 : Why doesn't abc prevent instantiation?

python - 如何将 Pylint 或其他 linters 与 Jupyter 笔记本一起使用?

Python abc.abstractproperty 兼容性

python - 来自数字模块的 ABC 类数字

python pandas 标志如果列中的每个值有多个唯一行

python - 是否可以在 tensorflow 中跨多个 GPU 拆分网络?

python - Pylint:在 "else"(no-else-return)警告后禁用不必要的 "return"

python - 从 pylint 了解 "Too many ancestors"