程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python with context management

編輯:Python

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 .

with working principle

  • 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 .

  • exc_type: Wrong type
  • exc_val: The value corresponding to the error type
  • exc_tb: The location of the error in the code

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved