decorator.py 887 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 = foo_decorator(u)
  24. # The @foo_decorator syntax is just shorthand for calling
  25. # foo_decorator on the decorated object right after its
  26. # declaration.
  27. v.f1()
  28. v.f2()
  29. if __name__ == '__main__':
  30. main()