Mixin and super()

less than 1 minute read

When working with Huggingface, there are lots of classes with suffix Mixin. I never thought about it’s actually meaning, but turn out to be an important feature.

Python, unlike some other Object-Oriented languages such as Java or C#, permits multiple inheritance.

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

  • You want to provide a lot of optional features for a class.
  • You want to use one particular feature in a lot of different classes.

1 Mixin examples

Here is a pizza baking class example:

class PlainPizza:
    def __init__(self):
        self.toppings = []
class OlivesMixin:
    def add_olives(self):
        print("Adding olives!")
        self.toppings += ['olives']
class SistersPizza(OlivesMixin, PlainPizza):
    def prepare_pizza(self):
        self.add_olives()

You can also add multiple Mixin but the main parent class should always be the right-most in the list of superclasses.

# PlainPizza is be the right-most
class MyPizza(OlivesMixin, SausagesMixin, PlainPizza):
    ... 

You can also print out the MRO (Method Resolution Order) of a class by print(ClassName.__mro__)

2 super()

  • Since Python3, we can direclty use super() instead of super(ChildClass, self) in Python2
  • super() would call all parents classes in multi-inheritance.

Tags:

Categories:

Updated: