What is a mixin, and why are they useful?

后端 未结 16 2147
無奈伤痛
無奈伤痛 2020-11-22 00:18

In \"Programming Python\", Mark Lutz mentions \"mixins\". I\'m from a C/C++/C# background and I have not heard the term before. What is a mixin?

Reading between the

16条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:02

    I think previous responses defined very well what MixIns are. However, in order to better understand them, it might be useful to compare MixIns with Abstract Classes and Interfaces from the code/implementation perspective:

    1. Abstract Class

    • Class that needs to contain one or more abstract methods

    • Abstract Class can contain state (instance variables) and non-abstract methods

    2. Interface

    • Interface contains abstract methods only (no non-abstract methods and no internal state)

    3. MixIns

    • MixIns (like Interfaces) do not contain internal state (instance variables)
    • MixIns contain one or more non-abstract methods (they can contain non-abstract methods unlike interfaces)

    In e.g. Python these are just conventions, because all of the above are defined as classes. However, the common feature of both Abstract Classes, Interfaces and MixIns is that they should not exist on their own, i.e. should not be instantiated.

提交回复
热议问题