Skip to content

Instantly share code, notes, and snippets.

@nicr9
Created January 20, 2016 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicr9/cb79b8367bc25ee00c6d to your computer and use it in GitHub Desktop.
Save nicr9/cb79b8367bc25ee00c6d to your computer and use it in GitHub Desktop.
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.
"""
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