What is a mixin, and why are they useful?

后端 未结 16 2475
無奈伤痛
無奈伤痛 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:25

    I think of them as a disciplined way of using multiple inheritance - because ultimately a mixin is just another python class that (might) follow the conventions about classes that are called mixins.

    My understanding of the conventions that govern something you would call a Mixin are that a Mixin:

    • adds methods but not instance variables (class constants are OK)
    • only inherits from object (in Python)

    That way it limits the potential complexity of multiple inheritance, and makes it reasonably easy to track the flow of your program by limiting where you have to look (compared to full multiple inheritance). They are similar to ruby modules.

    If I want to add instance variables (with more flexibility than allowed for by single inheritance) then I tend to go for composition.

    Having said that, I have seen classes called XYZMixin that do have instance variables.

提交回复
热议问题