Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- # -*- coding: utf-8 -*-
- """
- Learning me some context managers
- """
- # NOTE: see also: contextlib.contextmanager
- class Context(object):
- """
- Context to learn
- """
- def __init__(self):
- self.param = "init"
- def set_param(self, param):
- """
- sets this object's param
- """
- self.param = param
- def get_param(self):
- """
- returns this object's param
- """
- return self.param
- def __enter__(self):
- self.param = "enter"
- return self
- def __exit__(self, *args, **kwargs):
- self.param = "exit"
- def __str__(self):
- return "Context(param={})".format(self.param)
- def __repr__(self):
- return self.__str__()
- def main():
- """
- main func
- """
- ctx = Context()
- print("init:", ctx)
- print()
- ctx2 = Context
- print("class:", ctx2)
- with Context() as ctx2:
- print("init context:", ctx2)
- print("post init context:", ctx2)
- print()
- ctx3 = Context()
- print("pre-init:", ctx3)
- with ctx3 as ctx3:
- print("pre-init context:", ctx3)
- print("post pre-init context:", ctx3)
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment