Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Mixin Recipe
# http://littletutorials.com/2008/06/23/inheritance-not-for-code-reuse/
def mixin(mixin_cls):
def mixin_decorator(cls):
if not hasattr(cls, '__mixed__'):
cls.__mixed__ = []
for name, val in mixin_cls.__dict__.items():
if not name.startswith('__') and not name.endswith('__'):
if not hasattr(cls, name):
setattr(cls, name, val)
cls.__mixed__.append(name)
return cls
return mixin_decorator
#!/usr/bin/env python
from mixin import mixin
class MixinMixin(object):
def a_thing(self):
return "This is a Thing!!!"
@mixin(MixinMixin)
class MyMixin(object):
def i_want_this_one(self):
return "This one"
def also_this_one(self):
return "this also"
def this_one_also(self):
return "again!"
class AnotherMixin(object):
def here_is_something_great(self):
return "WOO!!!!!!"
@mixin(AnotherMixin)
@mixin(MyMixin)
class MyClass(object):
def mything(self):
return "I'm doing my own thing here"
if __name__ == '__main__':
print("yo!")
my_class = MyClass()
print my_class.mything()
print my_class.a_thing()
print my_class.i_want_this_one()
print my_class.also_this_one()
print my_class.this_one_also()
print my_class.here_is_something_great()
print my_class.__class__.__bases__ #Look MA! No extra parent classes!!!
print "I just mixed in %s" % my_class.__mixed__
yo!
I'm doing my own thing here
This is a Thing!!!
This one
this also
again!
WOO!!!!!!
(<type 'object'>,)
I just mixed in ['this_one_also', 'i_want_this_one', 'also_this_one', 'a_thing', 'here_is_something_great']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.