Skip to content

Instantly share code, notes, and snippets.

Created January 20, 2016 23:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Python decorators with classes
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.
return wrapped
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