While I pair with coworker, we get to read about Python mixins. I was aware of the existence of mixins but I haven’t actually read about them in details so it was a good opportunity for me to learn.
What is mixins in Python?
A mixin is a class that provides method implementations for reuse by multiple related child classes,
specifically methods that child classes can utilize with. A mixin class is not considered
a base class itself nor intended for direct instantiation. Typically, a child class that inherits
the mixin class uses multiple inheritance. Since Python doesn’t have a formal way of defining mixin
classes, it’s a good practice to name mixin classes with the suffix Mixin.
Example
This example is from pythontutorial.net.
Define a Person class:
class Person:
def __init__(self, name):
self.name = name
Define an Employee class that inherits from the Person class:
class Employee(Person):
def __init__(self, name, skills, dependents):
super().__init__(name)
self.skills = skills
self.dependents = dependents
Create an instance of the Employee class:
if __name__ == '__main__':
e = Employee(
name='John',
skills=['Pythoning Programming'],
dependents={'wife': 'Jane', 'children': ['Bob']}
)
Now, if we want to convert Employee object to a dictionary, we can add a new method for doing that.
However, if we want to convert objects of other classes to a dictionary as well, we can do it through
mixins which allow us reuse code for different classes.
For instance, we can create a mixin class called DictMixin:
class DictMixin:
def to_dict(self):
return self._traverse_dict(self.__dict__)
...
Now that we have DictMixin, our Employee class can inherit from it to use to_dict() method:
class Employee(DictMixin, Person):
def __init__(self, name, skills, dependents):
super().__init__(name)
self.skills = skills
self.dependents = dependents
if __name__ == '__main__':
e = Employee(
name='John',
skills=['Pythoning Programming'],
dependents={'wife': 'Jane', 'children': ['Bob']}
)
e.to_dict()
note: we need to specify the mixin classes before other classes.