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

Python context manager usage scenarios and exception handling

編輯:Python

Catalog

introduction

1、 Let's start with the simplest example ,with sentence

2、 What is context manager ?

3、 The principle of the context manager is as follows :

4、 Application scenarios of context manager :

4.1 Database connection

4.2 Exception handling for context manager

introduction

Use context manager , Can make the code more elegant and concise . Of course , The role of context manager is more than that , Its internal implementation mechanism , Can handle code exception very well , Improve code reusability

1、 Let's start with the simplest example ,with sentence # Create a file, write a string “Python”f = open('123.txt', 'w')f.write("python")f.close()# Use with Statement call context to implement file write operation with open('123.txt', 'w') as f: f.write('python')2、 What is context manager ?

The context is context Literal translation , It is used to represent the environment before and after code execution , For example, during file operation , The file needs to be opened and closed , The file read and write operation is in the context of file operation ;

Context manager , Context manager is defined as before a piece of code is executed , Perform some preprocessing work , Do some cleanup after the code is executed .

The context manager has enter() and exit() Two methods ,enter() Method in execution with The following statement is executed , It is generally used to deal with the content before operation , For example, some create objects , Initialization etc. ; exit() Method in with After the code in is executed , It's usually used to deal with the aftermath , Like closing files , Database shut down, etc .

3、 The principle of the context manager is as follows :

call enter() Method , Carry out pretreatment operation

Perform user actions

call exit() Method , Finish cleaning up

4、 Application scenarios of context manager :

Resource management function , File processing 、 network connections 、 Database connection and other operations need to close resources .

You can also add functionality before and after code execution , It's like a decorator , For example, do permission verification before code .

4.1 Database connection import pymysqlclass DBConnection(object): def __init__(self,ip,user,passwd,db): self.ip = ip self.user = user self.passwd = passwd self.db = db def __enter__(self): self.conn = pymysql.connect(self.ip, user=self.user, passwd=self.passwd, db=self.db) self.cur = conn.cursor() return self.cur def __exit__(self, exc_type, exc_val, exc_tb): self.cur.close() self.conn.close()with DBConnection('192.168.121.xxx', user="xxx", passwd="123456", db="xxx") as cur: cur.execute("select * from studnet;") result = cur.fetchall() print(result)

complete DBConnection This class , Every time you connect to the database , Simply call with Sentence can be used , Don't care about database shutdown 、 Abnormal etc.

4.2 Exception handling for context manager class MyOpen(object): """ Custom context management class """ def __init__(self, file, mode): self._file = file self._mode = mode def __enter__(self): self._handle = open(self._file, self._mode) return self._handle def __exit__(self, exc_type, exc_val, exc_tb): # print('Type: ', exc_type) # print('Value:', exc_val) # print('TreacBack:', exc_tb) self._handle.close() print(" Exception has been handled ") return True# Open the file in read mode , Write operation , I won't support it with MyOpen('123.txt', 'r') as f: f.write('python')# Output : Exception has been handled

with Syntax not only simplifies the subsequent cleanup of resource operations , It can be replaced try/finally Do exception handling

When with When an exception occurs in a statement executed in , Exception information will be sent to exit() Method , exit() The method has the following three parameters :

exc_type : Exception types

exc_val : outliers

exc_tb : Exception backtracking

All three parameters are related to the exception ,with Statement will put the exception exc_type ,exc_val and exc_tb Pass to exit() Method , It makes exit() Method to handle exceptions , If exit() The return is True, So this exception is ignored , And throw it in the way we define it . If exit() The return is True Anything other than , So this exception will be with Statement throw .

That's all python Context manager usage scenarios and details of exception handling , More about python For information about the exception handling of the context manager, please pay attention to other relevant articles on the software development network !



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