Created
November 23, 2016 02:30
-
-
Save gjcourt/008b119f47a5e099e505b7b3721ded36 to your computer and use it in GitHub Desktop.
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
class Implementation(object): | |
def __init__(self, func, x): | |
self.func = func | |
self.x = x | |
def __call__(self, *args, **kwargs): | |
return self.decorator(*args, **kwargs) | |
def decorator(self, *args, **kwargs): | |
y = 10 | |
print "x + {0} = {1}".format(y, self.x + y) | |
return self.func(*args, **kwargs) | |
class DescriptorDecorator(object): | |
def __init__(self, klass, x=None): | |
self.klass = klass | |
self.x = x | |
def __call__(self, func): | |
self.func = func | |
return self | |
def __get__(self, obj, type=None): | |
# Reflect bound method to wrapped class method | |
return self.klass(self.func.__get__(obj, type), x=self.x) | |
def my_decorator(x=None): | |
return DescriptorDecorator(Implementation, x=x) | |
class SomeClass(object): | |
@my_decorator(x=5) | |
def foo(self): | |
print 'Foo' | |
if __name__ == '__main__': | |
instance = SomeClass() | |
print instance.foo | |
instance.foo() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment