Created
January 9, 2021 11:07
-
-
Save stellasia/0121ab0880112365041218d8252d432e to your computer and use it in GitHub Desktop.
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
| """ | |
| Method decorators | |
| """ | |
| def decorate(param): | |
| def decorated(meth): | |
| """Just attach an attribute to the decorated method""" | |
| meth._is_decorated = True | |
| meth._param = param | |
| return meth | |
| return decorated | |
| class Base(type): | |
| def __init__(cls, name, bases, attrs): | |
| cls._decorated = [] | |
| for an, a in attrs.items(): | |
| if getattr(a, "_is_decorated", None): | |
| cls._decorated.append(an) | |
| # print(cls._decorated) | |
| type.__init__(cls, name, bases, attrs) | |
| class Class(metaclass=Base): | |
| def __init__(self): | |
| pass | |
| def get_all_decorated(self): | |
| return {a: { | |
| "text": getattr(self, a)(), | |
| "param": getattr(getattr(self, a), "_param") | |
| } for a in self._decorated | |
| } | |
| class AClass(Class): | |
| @decorate(param="TestClass") | |
| def decorated(self): | |
| return "a text" | |
| class BClass(Class): | |
| @decorate(param="TestClass") | |
| def decorated(self): | |
| return "a decorated method" | |
| @decorate(param="AClass") | |
| def another_decorated(self): | |
| return "another decorated method" | |
| if __name__ == '__main__': | |
| ac = AClass() | |
| print(ac.get_all_decorated()) | |
| assert ac.get_all_decorated() == { | |
| 'decorated': {'text': 'a text', 'param': 'TestClass'} | |
| } | |
| bc = BClass() | |
| print(bc.get_all_decorated()) | |
| assert bc.get_all_decorated() == { | |
| 'decorated': {'text': 'a decorated method', 'param': 'TestClass'}, | |
| 'another_decorated': {'text': 'another decorated method', 'param': 'AClass'} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment