Python mixin is the best way to achieve multiple inheritance . Python mixin is special type of python class which supports “mix in” of classes.
How to implement python mixin?
Method 1: Mixin without overriding-
Here we will not use any function overriding in underlines classes. It means
Step 1: Class creation-
Lets create two or more simple python classes.
class Example_mixin_class1(object):
def fun_A(self):
print("Example_mixin_class1")
class Example_mixin_class2(object):
def fun_B(self):
print("Example_mixin_class2")
Step 2: Mixin Class
In the above step, We have created two dummy classes with a different sets of functions. In this section, we will mixin them.
class MasterClass(Example_mixin_class2,Example_mixin_class1):
pass
The most important thing is that Python gives overriding priority from right to left.
Step 3 : Calling the function –
Lets create the object of the MasterClass class. Then we will call the fun_A() and fun_B() function.
master_class=MasterClass()
master_class.fun_A()
master_class.fun_B()
Let’s the code and see the output.

Method 2: Mixin with overriding-
Unlike the above section here will create two classes. These classes will be having functions with the same name and parameter. It means we will override a function in two classes.
Step 1: Class creation with overriding function
Here are two classes with function overriding.
class Example_mixin_class1(object):
def fun(self):
print("Example_mixin_class1")
class Example_mixin_class2(object):
def fun(self):
print("Example_mixin_class2")
Step 2: Mixin class-
Let’s create a master class that inherits the mixin class.
class MasterClass(Example_mixin_class2,Example_mixin_class1):
pass
Step 3: Object creating and function calling-
After creating the object of MasterClass and then we will invoke the fun() function. Here interesting thing is that fun() is common on both the mixin class. Lets see which one is invoke!
master_class=MasterClass()
master_class.fun()

It is invoking the fun() definition of Example_mixin_class2
because of Python Right to Left Hirarchy. If we change the order then it will invoke the function of Example_mixin_class1 . Let’s change and see the results.
class MasterClass(Example_mixin_class1, Example_mixin_class2):
pass
master_class=MasterClass()
master_class.fun()

Conclusion –
Mixin makes code more organized. It makes code more readable and performance wise more efficient. I hope this article must have clear your basics of Mixin class in python.
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.