Created
June 7, 2013 15:11
-
-
Save kgriffs/5729976 to your computer and use it in GitHub Desktop.
Example of dynamically decorating a method in Python
This file contains hidden or 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
import functools | |
class Scooby(object): | |
def mood(self): | |
return 'frightended' | |
def scooby_snack(func): | |
@functools.wraps(func) | |
def brave(self): | |
return 'not ' + func(self) | |
return brave | |
scooby = Scooby() | |
print('Scooby: <' + scooby.mood() + '>') | |
print('Fred: Would you do it for a Scooby Snack?') | |
Scooby.mood = scooby_snack(Scooby.mood) | |
print('Scooby: <' + scooby.mood() + '>') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment