context_1.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Создание своего контекстного менеджера
  2. class CustomManagerContext:
  3. def __enter__(self):
  4. print('Start manager context')
  5. return "This is value as ..."
  6. def __exit__(self, exc_type, exc_val, exc_tb):
  7. print('End manager context')
  8. print(exc_type, exc_val, exc_tb, sep=',')
  9. if isinstance(exc_val, ZeroDivisionError):
  10. print('Нельзя делить на ноль')
  11. return True
  12. # return True # без этой строки может быть исключение
  13. class FileContext:
  14. def __init__(self, path, mode):
  15. self.path = path
  16. self.mode = mode
  17. def __enter__(self):
  18. print("Open file")
  19. self.file = open(self.path, self.mode)
  20. return self.file
  21. def __exit__(self, exc_type, exc_val, exc_tb):
  22. print("Close file")
  23. self.file.close()
  24. def test_2():
  25. with FileContext('file.txt', 'r') as file:
  26. print(file.read())
  27. def test_1():
  28. # with open('text.txt', 'r') as file:
  29. # file.read()
  30. with CustomManagerContext() as cust:
  31. print(cust)
  32. print('hello')
  33. 1/0
  34. def main():
  35. # test_1()
  36. test_2()
  37. if __name__ == '__main__':
  38. main()