DRY and Reusable Code: How Python Mixins Improve Class Implementations

Ridwan Yusuf
1 min readJan 9, 2023

--

Mixin provides a way to add extra functionalities(methods) and attributes to another class.

Though it’s defined technically as a class in python,
it is widely used to add certain method implementation to an existing class.

Mixing provides an actual implementation, it makes code DRY (no repetition of implementation) and reusable

The convention for naming a mixin is to add Mixin to the class name.
A sample code snippet below:

[*]Mixin:

class MoveMixin:
def move(self):
print(f'{self.__class__.__name__} is moving')

__class__.__name__ gets the name of the current class

[*] classes definition

class Cat(MoveMixin):
def jump(self):
print('Cat jumps')

class Dog(MoveMixin):
def bite(self):
print('Dog bites')

[*]usage
dog = Dog().move()
cat = Cat().move()

[*]output
Dog moves
Cat moves

With this we are able to reuse an actual move() implementation without repeating it in each of the main classes(Dog, Cat)

Note:We use the keyword ‘class’ in Mixin defenition. That doesn’t mean it should be instantiated(though it can be instantiated because Python supports it )

Mixin should not be confused with Interface. They are two different things. Interface ensures that a concrete class must implement a method while mixin provides implement of the functionality.

Here is the link to explanation on Interface

--

--

Ridwan Yusuf
Ridwan Yusuf

Written by Ridwan Yusuf

RidwanRay.com -I provide engineers with actionable tips and guides for immediate use

No responses yet