『Effective Python』の続き。多重継承は日の目を見るか。 www.effectivepython.com
多重継承は一般的に避けましょうとしつつ、どうしても使いたい場合はMix-inを検討しましょうという話である。 Mix-inというとRubyが思い浮かぶが、別にRubyの専売特許ではなくPythonでも可能である。
二分木の構成したりJSONの取り扱いを例に説明しているが、大体タイトルがすべてを物語っている。
こちらがMix-inの例である。
class ToDictMixin(object): def to_dict(self): return self._traverse_dict(self.__dict__) def _traverse_dict(self, instance_dict): output = {} for key, value in instance_dict.items(): output[key] = self._traverse(key, value) return output def _traverse(self, key, value): if isinstance(value, ToDictMixin): return value.to_dict() elif isinstance(value, dict): return self._traverse_dict(value) elif isinstance(value, list): return [self._traverse(key, i) for i in value] elif hasattr(value, '__dict__'): return self._traverse_dict(value.__dict__) else: return value
class BinaryTree(ToDictMixin): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right tree = BinaryTree(10, left=BinaryTree(7, right=BinaryTree(9)), right=BinaryTree(13, left=BinaryTree(11))) print(tree.to_dict())