Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python Decorator
__author__ = 'Christoph Gerneth'
Decorators are one of the most powerful patterns. They can be used to
inject code in functions, modify them and infuence their beihavior.
Here is an example:
class Tools(object):
def sayhello(self, func):
def decorated(*args, **kwargs):
#excecute the decorated function:
result = func(*args, **kwargs)
#modify the restul here...
result = ' '.join(('Hello', str(result), 'some aditional foo'))
return result
#return the modified function. This is not a call!
return decorated
#Ok, now we decorate the targetfunction:
def dosomething(name):
return name.upper()
# ...and execute it.
print dosomething("Christoph")
# the result is "Hello CHRISTOPH some aditional foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment