The use of python's with

  with use of python                                      

  how it works           

After the statement following with is evaluated, the __enter__() method of the returned object is called, and the return value of this method will be assigned to the variable following as. When the code blocks after with are all executed, the __exit__() method of the previously returned object will be called

  code demo                  

1  class TestWith(object):
 2  
3      def  __init__ (self):
 4          super(). __init__ ()
 5  
6      # The __enter__() method will be executed after the statement following with is evaluated, and the return value of this method will be returned 
7      def  __enter__ ( self):
 8          print ( " I'm enter function " )
 9          return  " Foo " 
10  
11      # __exit__() method will be executed after the statement block after the with statement is executed 
12      def  __exit__ (self, types, value, true):
 13          print ("I'm exit function")
14 
15     def test(self):
16         print("I'm test")
17 
18 
19 with TestWith() as t:
20     print(t)

 operation result:

After with calls the TestWith class, the __enter()__ method of the TestWith class will be executed first, and the return value of this method will be assigned to the t after as. After the code block below with is executed, the __exit__ of the TestWith class will be executed. ()method

1 I'm enter function
2 Foo
3 I'm exit function

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324659016&siteId=291194637