Python mixins with sample

LORY
2 min readDec 28, 2020

--

Mixin is a way to create duck type in python . It could be useful for code reuse in some cases

Use case #1 A way for a “light-weight multi inheritance”


>>> class parent1:
... def hello(self):
... print('hello')
...
>>> class parent2:
... def greeting(self):
... print('hi')
...
>>> class child(parent1, parent2):
... def hi(self):
... self.hello()
... self.greeting()
...
>>> c = child()
>>> c.hi()
hello
hi

when conflict ,the left most wins

>>> class Mixin1(object):
... def test(self):
... print ("Mixin1")
...
>>> class Mixin2(object):
... def test(self):
... print ("Mixin2")
...
>>> class MyClass(Mixin1, Mixin2):
... pass
...
>>> MyClass().test()
Mixin1

Use case #2 wrapper, adapter or factory functions

define the models

>>> class user_model :
... def __init__(self, name, email):
... self.name = name
... self.email = email
... def __repr__(self):
... return f'{self.name}, {self.email}'
...
>>> class customer_model:
... def __init__(self, name, id):
... self.name = name
... self.id = id
... def __repr__(self):
... return f'{self.name}, {self.id}'
...

define a testing factory (also could be wrapper or helper)

>>>
>>> class model_factory:
... def create_user(self, kwargs):
... return user_model(**kwargs)
... def create_customer(self, kwargs):
... return customer_model(**kwargs)
...
>>>

a testing service

>>> class service(model_factory):
... def test(self):
... print(self.create_user({'name':'123','email':'test@gmail.com'}))
... print(self.create_customer({'name':'456','id':1}))
...
>>> service().test()
123, test@gmail.com
456, 1

Mixin brings the code reusability from factory class or wrapper , adapter or converter .A mixin works as a kind of inheritance, but instead of defining an “is-a” relationship it may be more accurate to say that it defines an “includes-a” relationship

It has more focus on how “group” similar functions into classes then reuse by inheritance ;plus import and decorator which provides complete flexibility how to reuse code and get better structure.

--

--

LORY
LORY

Written by LORY

A channel which focusing on developer growth and self improvement

Responses (1)