How to use Mixin in Python?

Python Tutorials

Summary: In this tutorial, you will learn about Mixin classes in Python and how to use them in your python program with the help of an example.

A Mixin in Python is a base class that adds functionality to its subclasses through inheritance but is not intended to be instantiated itself.

The idea of Mixin class is not to create a base version of other classes, but to create a class only to provide functionality to other classes.

The methods which we define in a Mixin class will be utilized by the derived classes, and will essentially be mixed into them.

Let’s see an example of its use case.

Use Mixin in Python to Extend Functionality

Consider the following code for instance:

# Define Mixin class
class MyMixin:
    def setname(this, name):
        this.name = name
    def getname(this):
        return this.name


# Define a class that inherits Mixin
class MyClass(MyMixin):
    def __init__(self):
        self.name = "Adarsh"

# create object of class `MyClass`
my_object = MyClass()

username = my_object.getname()
print(username)

Output: Adarsh

This program has two classes, of which the first one (i.e. MyMixin) is a Mixin. We have created this class to define the setter and getter functionality for the instance variable name.

Now, as we have already inherited this Mixin class into MyClass, we can utilize the setter and getter function to update and fetch the instance variable name of MyClass:

my_object.setname("Pencil Programmer")
username = my_object.getname()

print(username)

Output: Pencil Programmer

So, this is how we can use Mixin to provide functionality to the derived classes.

In conclusion, Mixin class in Python is not meant to be a standalone object or parent class, but acts to add functionality to its clases which inherits it.

Leave a Reply

Your email address will not be published. Required fields are marked *