Created
December 16, 2019 16:17
-
-
Save Neanderthal/f2a2107c7c14cd21e5fadd4ffab94132 to your computer and use it in GitHub Desktop.
class decorator for timing
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
| #https://www.codementor.io/@sheena/advanced-use-python-decorators-class-function-du107nxsv | |
| def time_all_class_methods(Cls): | |
| class NewCls(object): | |
| def __init__(self,*args,**kwargs): | |
| self.oInstance = Cls(*args,**kwargs) | |
| def __getattribute__(self,s): | |
| """ | |
| this is called whenever any attribute of a NewCls object is accessed. This function first tries to | |
| get the attribute off NewCls. If it fails then it tries to fetch the attribute from self.oInstance (an | |
| instance of the decorated class). If it manages to fetch the attribute from self.oInstance, and | |
| the attribute is an instance method then `time_this` is applied. | |
| """ | |
| try: | |
| x = super(NewCls,self).__getattribute__(s) | |
| except AttributeError: | |
| pass | |
| else: | |
| return x | |
| x = self.oInstance.__getattribute__(s) | |
| if type(x) == type(self.__init__): # it is an instance method | |
| return time_this(x) # this is equivalent of just decorating the method with time_this | |
| else: | |
| return x | |
| return NewCls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment