with
Statement is suitable for accessing resources , Make sure that the necessary... Is executed regardless of whether an exception occurs during use “ clear ” operation , Release resources , For example, the file is automatically closed after use / Automatic acquisition and release of locks in threads .
Following the with
After the following statement is evaluated , Return object's __enter__()
Method is called , The return value of this method will be assigned to as
The latter variable .
When with After all the subsequent code blocks have been executed , Will call the... Of the previously returned object __exit__()
Method .
for example :
class SqlHelper(object):
def __enter__(self):
return 123
def __exit__(self, exc_type, exc_val, exc_tb):
print("in __exit__")
# establish Sqlhelper object
sqlhelper = SqlHelper()
with sqlhelper as f:
print(f)
Run the above code output :
123
in __exit__
explain with
Will execute first SqlHelper
The inside of the class __enter__()
Method , And will __enter__()
The return value of the method is assigned to the f
, So print out f
Namely __enter__()
The return value of .
When it's done , Will execute __exit__()
Method .
__exit__()
Methods include 3 Parameters , exc_type
, exc_val
, exc_tb
, These parameters are quite useful in exception handling .
for example :
class Sample():
def __enter__(self):
print('in enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print "type: ", exc_type
print "val: ", exc_val
print "tb: ", exc_tb
def do_something(self):
bar = 1 / 0
return bar + 10
with Sample() as sample:
sample.do_something()
Run program output :
in enter
Traceback (most recent call last):
type: <type 'exceptions.ZeroDivisionError'>
val: integer division or modulo by zero
File "/home/user/cltdevelop/Code/TF_Practice_2017_06_06/with_test.py", line 36, in <module>
tb: <traceback object at 0x7f9e13fc6050>
sample.do_something()
File "/home/user/cltdevelop/Code/TF_Practice_2017_06_06/with_test.py", line 32, in do_something
bar = 1 / 0
ZeroDivisionError: integer division or modulo by zero
Process finished with exit code 1