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
的情况下通过,同时使用抽象属性来确保继承合同是明确的?