-
-
Save ianb/164136 to your computer and use it in GitHub Desktop.
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 decorator | |
def multiplier(n): | |
def decorator(fn): | |
return Multiplier(fn, n) | |
return decorator | |
class Multiplier(object): | |
def __init__(self, func, n): | |
self.func = func | |
self.n = n | |
def __call__(self, arg): | |
return self.func(arg*self.n) | |
def __get__(self, obj, type=None): | |
if hasattr(self.func, '__get__): | |
return self.__class__(self.func.__get__(obj, type), self.n) | |
return self | |
@multiplier(3) | |
def foo(arg): | |
print arg | |
foo(4) | |
class bar(object): | |
@multiplier(4) | |
def foo(self, arg): | |
print self | |
print arg | |
@multiplier(5) # this won't work, since baz takes two arguments, but the decorator does not. | |
def baz(self, arg): | |
print self | |
print arg | |
bar().foo(4) | |
bar().baz(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment