Skip to content

Instantly share code, notes, and snippets.

@docsteveharris
Created July 10, 2017 14:20
Show Gist options
  • Save docsteveharris/7693d78e235b0d354cdc5b56ef264280 to your computer and use it in GitHub Desktop.
Save docsteveharris/7693d78e235b0d354cdc5b56ef264280 to your computer and use it in GitHub Desktop.
class MixinOne(object):
def print_name(self):
print("{} is using MixinOne.".format(self.name))
class MixinTwo(object):
def print_name(self):
print("{} is using MixinTwo.".format(self.name))
class AutoMixinMeta(type):
def __call__(cls, *args, **kwargs):
try:
mixin = kwargs.pop('mixin')
name = "{}With{}".format(cls.__name__, mixin.__name__)
cls = type(name, (mixin, cls), dict(cls.__dict__))
except KeyError:
pass
return type.__call__(cls, *args, **kwargs)
class Sub(object):
__metaclass__ = AutoMixinMeta
def __init__(self, name):
self.name = name
s = Sub('foo', mixin=MixinOne)
s.print_name()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment