decorator.py 938 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python"""
  4. class foo_decorator(object):
  5. def __init__(self, decoratee):
  6. self._decoratee = decoratee
  7. def f1(self):
  8. print("decorated f1")
  9. self._decoratee.f1()
  10. def __getattr__(self, name):
  11. return getattr(self._decoratee, name)
  12. class undecorated_foo(object):
  13. def f1(self):
  14. print("original f1")
  15. def f2(self):
  16. print("original f2")
  17. @foo_decorator
  18. class decorated_foo(object):
  19. def f1(self):
  20. print("original f1")
  21. def f2(self):
  22. print("original f2")
  23. def main():
  24. u = undecorated_foo()
  25. v = foo_decorator(u)
  26. # The @foo_decorator syntax is just shorthand for calling
  27. # foo_decorator on the decorated object right after its
  28. # declaration.
  29. v.f1()
  30. v.f2()
  31. if __name__ == '__main__':
  32. main()