decorator.py 965 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python
  2. class foo_decorator(object):
  3. def __init__(self, decoratee):
  4. self._decoratee = decoratee
  5. def f1(self):
  6. print("decorated f1")
  7. self._decoratee.f1()
  8. def __getattr__(self, name):
  9. return getattr(self._decoratee, name)
  10. class undecorated_foo(object):
  11. def f1(self):
  12. print("original f1")
  13. def f2(self):
  14. print("original f2")
  15. @foo_decorator
  16. class decorated_foo(object):
  17. def f1(self):
  18. print("original f1")
  19. def f2(self):
  20. print("original f2")
  21. def main():
  22. u = undecorated_foo()
  23. v = decorated_foo()
  24. # This could also be accomplished by:
  25. # v = foo_decorator(undecorated_foo)
  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()