Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Last active November 21, 2018 06:06
Show Gist options
  • Save tonyseek/3fc6567a4238a6b80ee3b417f46ead1b to your computer and use it in GitHub Desktop.
Save tonyseek/3fc6567a4238a6b80ee3b417f46ead1b to your computer and use it in GitHub Desktop.
The decorator on instance method as a descriptor
import functools
class Increment(object):
def __init__(self, wrapped, delta):
self.wrapped = wrapped
self.delta = delta
def __get__(self, instance, owner=None):
method = self.wrapped.__get__(instance, owner)
if instance is None:
return method # unbound method
@functools.wraps(method)
def wrapper(*args, **kwargs):
instance.n += self.delta # no more inspect.getcallargs
return method(*args, **kwargs)
return wrapper
def increment(delta):
def decorator(wrapped):
return Increment(wrapped, delta)
return decorator
class Foo(object):
def __init__(self, n):
self.n = n
@increment(2)
def foo(self):
return self.n
foo = Foo(40)
print(foo.foo())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment