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

Implementation of Python context manager protocol

編輯:Python

Catalog

Preface

todo: edition 1

todo: edition 2

Preface

In 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 !



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