Jaybanuan's Blog

どうせまた調べるハメになることをメモしていくブログ

PythonにおけるMixin

PythonにおけるMixinについて、以下のブログの説明が分かりやすかった。

www.thedigitalcatonline.com

Mixinの説明を以下に引用する。

Python doesn't provide support for mixins with any dedicated language feature, so we use multiple inheritance to implement them. This clearly requires great discipline from the programmer, as it violates one of the main assumptions for mixins: their orthogonality to the inheritance tree. In Python, so-called mixins are classes that live in the normal inheritance tree, but they are kept small to avoid creating hierarchies that are too complicated for the programmer to grasp. In particular, mixins shouldn't have common ancestors other than object with the other parent classes.

一部補足して意訳すると、以下のようになる。

PythonはMixinに対応するための専用の言語機能を提供していないため、Mixinを実装するには多重継承を代用することになります。ところが、何の制約もなく自由に多重継承を利用すると、Mixinの根幹をなす前提である継承ツリーの直交性を乱すことになるため、プログラマによる優れた規律(コーディングルール)が明らかに必要になります。Pythonにおいては、Mixinと呼ばれるものは通常の継承ツリーに現れるクラスですが、プログラマが把握不能に陥るような複雑な階層にならないように、そのクラスは小さく保つ必要があります。特に、Mixinは(埋め込み先のクラスに対して)object以外の他の親クラスを共通の祖先に持つべきではありません。

要するに「PythonではMixinは言語機能じゃなくてコーディングルール」ということのよう。