Preface
todo: edition 1
todo: edition 2
PrefaceIn the context manager protocol , There are two magic methods involved __enter__ Method and __exit__ Method
stay python All objects that implement the context manager protocol in Can be used with operation
with Started the context manager of the object
Context Manager Protocol :
__enter__ Method : Get into enter The result returned by the method is as Subsequent variable reception
exit: sign out with All the statements in are executed perform exit
Implement a simple file operation to see the context manager protocol :
class MyOpen: # Instantiation def __init__(self, filename, mode, encoding): self.filename = filename self.mode = mode self.encoding = encoding def __enter__(self): print("---enter--- Method ") # Execute file opening operation self.f = open(self.filename, self.mode, encoding=self.encoding) return self.f def __exit__(self, exc_type, exc_val, exc_tb): """ :param exc_type: Exception types :param exc_val: Abnormal information :param exc_tb: Exception traceability object :return: """ print('----enter---') self.f.close()with MyOpen('hr.txt', 'w', encoding='utf-8') as f: print(f.write(' The file is currently open , Write data :23323232'))
use pymysql Implement a class that operates the database , Implement the context manager protocol , When implementing the exit context , Automatically close the cursor , disconnect
todo: edition 1# todo: edition 1:class mysql_db(object): # Instantiate properties def __init__(self):
1. Connect to database
self.cou = pymysql.connect( host= " Database host address ", port= port , user=" Login database account ", password=" Password to log in to the database ", database=" Database name ", charset='utf8', Coding format cursorclass=pymysql.cursors.DictCursor Convert the default tuple format to dictionary format output )
2. Create cursors
self.cur = self.cou.cursor() def __enter__(self): return self.cur return cur object def __exit__(self, exc_type, exc_val, exc_tb): """ :param exc_type: Exception types :param exc_val: Abnormal information :param exc_tb: Exception traceability object :return: """ # Close cursor self.cur.close() # Close database connection self.cou.close()def Obtain_one_date(): with mysql_db() as db: db.execute('select * from t_customer LIMIT 4') Use execute Method to execute a query statement content = db.fetchone() Returns the result of a query for a piece of data print(content)# Function call Obtain_one_date()
todo: edition 2sql = 'select * from t_customer LIMIT 4'def mysql_db1(**kwargs): return pymysql.connect(host=kwargs.get('host', 'xxxx'), user=kwargs.get("user",'xxxx'), passwd=kwargs.get("passwd",'xxxx'), database=kwargs.get("database",'xxxx'), port=kwargs.get('port', xxxx), charset=kwargs.get('charset', 'utf8'))
1. Create database connection object
cou = mysql_db1()
2. Create cursors
with cou.cursor() as cu: cu.execute(sql) Use execute Method to execute a query statement commt = cu.fetchone() Returns the result of a query for a piece of data print(commt)# Function call mysql_db1()
This is about python This is the end of the article on the implementation of the context manager protocol , More about python Context manager Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !
Catalog Running effect How t
p{margin:10px 0}.markdown-body
1、開運算先腐蝕後膨脹的操作稱為開運算The role of