Skip to content

Instantly share code, notes, and snippets.

Embed
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.
[wikipedia](https://en.wikipedia.org/wiki/Decorator_pattern)
Here is an example:
'''
class Tools(object):
@classmethod
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:
@Tools.sayhello
def dosomething(name):
#whatever-code
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