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}
プロパティが Human の派生クラスに必要であることを明確にしたいと思いderived_config
ます。このプロパティを設定しない派生クラスのコードは実行されないという意味で、抽象プロパティ デコレーターがトリックを行います。
ただし、pylint は次のエラーで失敗します。
W: 39, 0: Method 'derived_config' is abstract in class 'Human' but is not overridden (abstract-method)
注意:
- pylintは抽象プロパティに対して不平を言いませんが、パターンは同じです (ターミナル リーフである
implementation_config
ことを除いて)。OneHandedClown
- クラス変数 implementation_config を削除すると、pylintは文句を言います
OneHandedClown
pylint-disable
継承コントラクトが明示的であることを確認するために抽象プロパティを使用すると同時に、使用せずに lint が確実に通過するようにするにはどうすればよいですか?