TelenkovDmitry 6 месяцев назад
Родитель
Сommit
eb266d5e43

+ 21 - 4
courses/python_oop/abstract/iter_3.py

@@ -186,9 +186,6 @@ class LibraryIterator:
 
         return page
         
-
-
-
 def test_5():
     book1 = Book("Book 1", ["Page 1", "Page 2", "Page 3", "Page 4"])
     book2 = Book("Book 2", ["Page A", "Page B", "Page C"])
@@ -207,6 +204,25 @@ def test_5():
     for page in library:
         print(page)
 
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~        
+
+class InfinityIterator:
+
+    def __init__(self, start=0):
+        self.value = start
+
+    def __iter__(self):
+        return self
+
+    def __next__(self):
+        foo = self.value
+        self.value += 10
+        return foo
+
+def test_6():
+    for i in InfinityIterator(7):
+        print(i)
+
 
 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~        
 
@@ -237,7 +253,8 @@ def main():
     # test_2()
     # test_3()
     # test_4()
-    test_5()
+    # test_5()
+    # test_6()
 
 if __name__ == '__main__':
     main()

+ 50 - 0
courses/python_oop/manager/context.py

@@ -0,0 +1,50 @@
+# Создание своего контекстного менеджера
+
+class CustomManagerContext:
+    def __enter__(self):
+        print('Start manager context')
+        return "This is value as ..."
+    
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        print('End manager context')
+        print(exc_type, exc_val, exc_tb, sep=',')
+        if isinstance(exc_val, ZeroDivisionError):
+            print('Нельзя делить на ноль')
+            return True
+        # return True # без этой строки может быть исключение
+
+class FileContext:
+    def __init__(self, path, mode):
+        self.path = path
+        self.mode = mode
+
+    def __enter__(self):
+        print("Open file")
+        self.file = open(self.path, self.mode)
+        return self.file
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        print("Close file")
+        self.file.close()
+
+
+def test_2():
+    with FileContext('file.txt', 'r') as file:
+        print(file.read())
+
+
+def test_1():
+    # with open('text.txt', 'r') as file:
+    #     file.read()
+    with CustomManagerContext() as cust:
+        print(cust)
+        print('hello')
+        1/0
+
+
+def main():
+    # test_1()
+    test_2()
+
+if __name__ == '__main__':
+    main()

+ 1 - 0
courses/python_oop/manager/file.txt

@@ -0,0 +1 @@
+Hello. This is sipmle text file.