Created
December 2, 2015 23:24
-
-
Save carlos-jenkins/9ff355d1a9a5a25cb8b7 to your computer and use it in GitHub Desktop.
Use metaclass to wrap methods in a object using a decorator.
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
from six import add_metaclass | |
def print_decorator(func): | |
def replacement(*args, **kwargs): | |
result = func(*args, **kwargs) | |
print('The result of the function is: {}'.format(result)) | |
return result | |
return replacement | |
class MyMetaclass(type): | |
def __new__(cls, name, parents, dct): | |
# Change methods | |
for method in ['myhamjam', 'myfoobar']: | |
dct[method] = print_decorator(dct[method]) | |
return super(MyMetaclass, cls).__new__(cls, name, parents, dct) | |
@add_metaclass(MyMetaclass) | |
class Original(object): | |
def myhamjam(self): | |
return 20 | |
def myfoobar(self, bar, extra=0): | |
return 10 + bar + extra | |
if __name__ == '__main__': | |
my = Original() | |
my.myhamjam() | |
my.myfoobar(20) | |
my.myfoobar(20, extra=100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment