Created
June 21, 2015 13:04
-
-
Save c7h/e2c73880159ab3502539 to your computer and use it in GitHub Desktop.
Python Decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__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