Skip to content

Instantly share code, notes, and snippets.

@alecordev
Last active July 24, 2018 16:27
Show Gist options
  • Save alecordev/e77b92c00d0fe2c2adea0e4282df6985 to your computer and use it in GitHub Desktop.
Save alecordev/e77b92c00d0fe2c2adea0e4282df6985 to your computer and use it in GitHub Desktop.
Python decorate instance method example - Timed decorator
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