Skip to content

Introduction

A mixin in python is a simple class used to add methods to another class. They should not have a parent (apart obviously from object).

Mixin

Parent a Class to add some extra functionality.

In contrast, a decorator is related but

Decorator

Add behaviour to an object dynamically.

Read this article :

visit

multiple inheritance

Since mixins are used to avoid problems with multiple inheritance here is a short description on how python multiple inheritance works.

Python uses the signature of classes to decide which method to call in a classic diamond problem situation.

It is called 'Method Resolution Order' so there is a member called mro to show how the ordering works.

For a more visual explanation see : visit

Multiple inheritance by signature
class Ancestor:
    def rewind(self):
        print("Ancestor: rewind")

class Parent1(Ancestor):
    def open(self):
        print("Parent1: open")

class Parent2(Ancestor):
    def open(self):
        print("Parent2: open")

    def close(self):
        print("Parent2: close")

    def flush(self):
        print("Parent2: flush")


class Child(Parent1, Parent2):
    def flush(self):
        print("Child: flush")


print(Child.__mro__)

c = Child()
c.rewind()
c.open()
c.close()
c.flush()

This will print :

(<class '__main__.Child'>, <class '__main__.Parent1'>, <class '__main__.Parent2'>, <class '__main__.Ancestor'>, <class 'object'>)
Ancestor: rewind
Parent1: open
Parent2: close
Child: flush

If you change the order in the inheritance sequence

Change ordering
...
class Child(Parent2, Parent1):
...

The output changes to :

(<class '__main__.Child'>, <class '__main__.Parent2'>, <class '__main__.Parent1'>, <class '__main__.Ancestor'>, <class 'object'>)
Ancestor: rewind
Parent2: open
Parent2: close
Child: flush

TODO

Finish this, ...