Guest User

Untitled

a guest
May 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. Learning me some context managers
  6. """
  7.  
  8. # NOTE: see also: contextlib.contextmanager
  9.  
  10. class Context(object):
  11. """
  12. Context to learn
  13. """
  14. def __init__(self):
  15. self.param = "init"
  16.  
  17. def set_param(self, param):
  18. """
  19. sets this object's param
  20. """
  21. self.param = param
  22.  
  23. def get_param(self):
  24. """
  25. returns this object's param
  26. """
  27. return self.param
  28.  
  29. def __enter__(self):
  30. self.param = "enter"
  31. return self
  32.  
  33. def __exit__(self, *args, **kwargs):
  34. self.param = "exit"
  35.  
  36. def __str__(self):
  37. return "Context(param={})".format(self.param)
  38.  
  39. def __repr__(self):
  40. return self.__str__()
  41.  
  42.  
  43. def main():
  44. """
  45. main func
  46. """
  47. ctx = Context()
  48. print("init:", ctx)
  49. print()
  50.  
  51. ctx2 = Context
  52. print("class:", ctx2)
  53. with Context() as ctx2:
  54. print("init context:", ctx2)
  55. print("post init context:", ctx2)
  56. print()
  57.  
  58. ctx3 = Context()
  59. print("pre-init:", ctx3)
  60. with ctx3 as ctx3:
  61. print("pre-init context:", ctx3)
  62. print("post pre-init context:", ctx3)
  63.  
  64.  
  65. if __name__ == '__main__':
  66. main()
Add Comment
Please, Sign In to add comment