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就会报错。
我该如何确保lint检查通过,而不使用pylint-disable
,同时又能使用抽象属性来确保继承的约定是明确的呢?
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
设置好,就足够在 Clown
里实现抽象属性,而之前在 Clown
里实现的 derived_config
却不够在 Human
里实现对应的抽象属性呢?