Skip to content

Instantly share code, notes, and snippets.

@c7h
Created June 21, 2015 13:04
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 c7h/e2c73880159ab3502539 to your computer and use it in GitHub Desktop.
Save c7h/e2c73880159ab3502539 to your computer and use it in GitHub Desktop.
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