You hear a lot about “mixins”, but what exactly is a mixin? And, how can you create your own?
A Mixin is a special kind of inheritance in Python (and other object-oriented languages) and it’s starting to get a big rise in Django / Web Application Development. You can use a Mixin to allow classes in Python to share methods between any class that inherits from that Mixin. So what does it look like?
This is an example from the Mixin Documentation on djangoproject.com. As you can see just looking at this example, it’s just a plain Python class.
Now, you can pass it in to a class and call the methods just as you would if the method was on the class as
This is useful if you have some code that you want to reuse among different classes in your code.
Can you think of a function that you would need to reuse in your code? Try this out! Create a Mixin and pass it into all the places that need some reusable code snippets!