Last active
January 25, 2018 18:14
-
-
Save kjaanson/4e5b58b5ff28c379bf8d8500c966c262 to your computer and use it in GitHub Desktop.
Dynamic addition of methods to class with decorators
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 MainClass: | |
DYN_METHOD_REGISTRY = {} | |
def __init__(self): | |
print(f"This class has dynamically added methods: {self.DYN_METHOD_REGISTRY.keys()}") | |
def runmethods(self): | |
for name, fp in self.DYN_METHOD_REGISTRY.items(): | |
fp(self,"test") | |
def add_dyn_method(name): | |
def decorator(func): | |
MainClass.DYN_METHOD_REGISTRY[name] = func | |
setattr(MainClass,func.__name__, func) | |
return func | |
return decorator | |
@add_dyn_method("foo") | |
def foo_processor(self, test): | |
print("foo") | |
@add_dyn_method("bar") | |
def bar_processor(self, test): | |
print("bar") | |
kala = MainClass() | |
kala.runmethods() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment