Python decorators with classes
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
class WithoutParams(object): | |
def __init__(self, func): | |
""" | |
Constructor receives target function. | |
""" | |
self.func = func | |
def __call__(self, *args, **kwargs): | |
""" | |
Arguments intended for target function are passed to __call__. | |
From here you can call the target any way you see fit. | |
""" | |
self.func("Never gonna give you up") | |
class WithParams(object): | |
def __init__(self, val): | |
""" | |
Constructor takes decorator params instead of target. | |
""" | |
self.val = val | |
def __call__(self, func): | |
""" | |
Target function is passed in here instead. | |
This is where we create a wrapper function to replace the target. | |
""" | |
def wrapped(*args, **kwargs): | |
""" | |
Wrapper function takes the target arguments and calls target. | |
""" | |
func(self.val) | |
return wrapped | |
@WithoutParams | |
def a(text): | |
print text | |
@WithParams("Never gonna let you down") | |
def b(text): | |
print text | |
if __name__ == "__main__": | |
a("hello world") | |
b("foo bar") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment