Created
September 6, 2012 10:24
-
-
Save niwinz/3654502 to your computer and use it in GitHub Desktop.
Dynamic Inheritance with python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DynamicInheritance(type): | |
""" | |
Dinamicaly modify class with some extra mixins. | |
""" | |
def __call__(cls, *args, **kwargs): | |
_mixins = kwargs.pop("_mixins", None) | |
if _mixins: | |
assert isinstance(_mixins, tuple), "_mixin patemeter must be a tuple" | |
new_cls = type(cls.__name__, _mixins + (cls,), {}) | |
return super(DynamicInheritance, new_cls).__call__(*args, **kwargs) | |
return super(DynamicInheritance, cls).__call__(*args, **kwargs) | |
class MyMixin1(object): | |
def test_method(self): | |
print("mixin1") | |
super().test_method() | |
class MyMixin2(object): | |
def test_method(self): | |
print("mixin2") | |
super().test_method() | |
class Foo(object, metaclass=DynamicInheritance): | |
def test_method(self): | |
print("Main method") | |
foo_instance = Foo(_mixins=(MyMixin2, MyMixin1)) | |
foo_instance.test_method() | |
# output: | |
# | |
# [3/5.0.0]{1}niwi@niwi:~/tmp> python3 dynamic_inheritance.py | |
# mixin2 | |
# mixin1 | |
# Main method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment