Last active
December 29, 2015 10:09
-
-
Save chengui/7655232 to your computer and use it in GitHub Desktop.
python: delegate implementation based on meta-class
This file contains 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 DelegateMetaClass(type): | |
def __new__(cls, name, bases, attrs): | |
methods = attrs.pop('delegated_methods', ()) | |
for m in methods: | |
def make_func(m): | |
def func(self, *args, **kwargs): | |
return getattr(self.delegate, m)(*args, **kwargs) | |
return func | |
attrs[m] = make_func(m) | |
return super(DelegateMetaClass, cls).__new__(cls, name, bases, attrs) | |
class Delegate(object): | |
__metaclass__ = DelegateMetaClass | |
def __init__(self, delegate): | |
self.delegate = delegate | |
class ImmutableList(Delegate): | |
delegated_methods = ( '__contains__', '__eq__', '__getitem__', '__getslice__', | |
'__str__', '__len__', 'index', 'count') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment