Skip to main content
 首页 » 编程设计

python之pylint 和 abc之抽象方法

2025年05月04日13yyy_WW

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 中实现相应的抽象属性吗?