-
-
Save alecordev/e77b92c00d0fe2c2adea0e4282df6985 to your computer and use it in GitHub Desktop.
Python decorate instance method example - Timed decorator
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
import types | |
class Timed(object): | |
def __init__(self, f): | |
self.func = f | |
def __call__(self, *args, **kwargs): | |
start = dt.datetime.now() | |
ret = self.func(*args, **kwargs) | |
time = dt.datetime.now() - start | |
ret["time"] = time | |
return ret | |
def __get__(self, instance, cls): | |
return types.MethodType(self, instance, cls) | |
class Test(object): | |
def __init__(self): | |
super(Test, self).__init__() | |
@Timed | |
def decorated(self, *args, **kwargs): | |
print(self) | |
print(args) | |
print(kwargs) | |
return dict() | |
def call_deco(self): | |
self.decorated("Hello", world="World") | |
if __name__ == "__main__": | |
t = Test() | |
ret = t.call_deco() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment