Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 lines of this example (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritances to extend a class as opposed to 'proper' subclassing. Is that right?

Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approaches be better than using composition?

What separates a mixin from multiple inheritances? Is it just a matter of semantics?

1 Answer

0 votes
by (106k points)

In Python, we have a simple type of multiple inheritances which allows the creation of mixins. mixins are classes that are used to "mix in" extra properties and methods into a class. This property of mixin allows you to create classes in a compositional style.

An example that illustrates the use of mixin:-

class Mixin1(object):

    def test(self):

        print ("Mixin1")

class Mixin2(object):

    def test(self):

        print ("Mixin2")

class MyClass(BaseClass, Mixin1, Mixin2):

    pass

In Python, the class hierarchy is defined right to left, so in this case, the Mixin2 class is the base class, extended by Mixin1 class and finally by BaseClass. It is fine because many times the mixin classes don't override each other's, or the base class' methods.  In your mixin class, this can lead to unexpected results if you override methods or properties because the priority of how methods are resolved is from left to right.

obj = MyClass()

obj.test()

So the correct way to use mixins is to use as we do in the reverse order which is as follows:

class MyClass(Mixin2, Mixin1, BaseClass):

    pass

Related questions

0 votes
1 answer
asked Jul 30, 2019 in Java by noah kapoor (5.3k points)
+1 vote
3 answers
asked May 18, 2019 in Python by Ayush (46k points)
0 votes
2 answers
0 votes
1 answer

Browse Categories

...