2
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不会抱怨 abstract property implementation_config,但模式是相同的(除了那OneHandedClown是一个终端叶)。
  • 如果我删除类变量 implementation_config ,pylint确实会抱怨OneHandedClown

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

4

1 回答 1

1

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

...


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足以实现 in 中的抽象属性Clown,而之前的实现derived_configinClown却不足以实现 in 中对应的抽象属性Human

于 2014-08-17T00:56:03.707 回答