這篇文章主要介紹了python上下文管理器協議怎么實現的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇python上下文管理器協議怎么實現文章都會有所收獲,下面我們一起來看看吧。
在上下文管理器協議的過程中,涉及到兩個魔術方法__enter__方法 和 __exit__方法
在python中所有實現了上下文管理器協議的對象 都可以用使用with操作
with啟動了對象的上下文管理器
上下文管理器協議:
__enter__方法: 進入enter方法返回的結果被as后面的變量接收
exit: 退出with中所有的語句執行完畢執行 執行 exit
實現一個簡單的文件操作來看下上下文管理器協議:
class MyOpen:
# 實例化
def __init__(self, filename, mode, encoding):
self.filename = filename
self.mode = mode
self.encoding = encoding
def __enter__(self):
print("---enter---方法")
# 執行文件打開操作
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: 異常類型
:param exc_val: 異常信息
:param exc_tb: 異常溯源對象
:return:
"""
print('----enter---')
self.f.close()
with MyOpen('hr.txt', 'w', encoding='utf-8') as f:
print(f.write('當前打開了文件,寫入了數據:23323232'))用pymysql實現一個操作數據庫的類,實現上下文管理器協議,實現退出上下文時,自動關閉游標,斷開連接
# todo:版本1: class mysql_db(object): #實例化屬性 def __init__(self):
1.連接數據庫
self.cou = pymysql.connect( host= "數據庫主機地址", port= 端口, user="登錄數據庫的賬號", password="登錄數據庫的密碼", database="數據庫名稱", charset='utf8', 編碼格式 cursorclass=pymysql.cursors.DictCursor 將默認的元組格式轉換成字典格式輸出 )
2.創建游標
self.cur = self.cou.cursor()
def __enter__(self):
return self.cur 返回cur對象
def __exit__(self, exc_type, exc_val, exc_tb):
"""
:param exc_type: 異常類型
:param exc_val: 異常信息
:param exc_tb: 異常溯源對象
:return:
"""
#關閉游標
self.cur.close()
# 關閉數據庫連接
self.cou.close()
def Obtain_one_date():
with mysql_db() as db:
db.execute('select * from t_customer LIMIT 4') 使用execute方法進行查詢語句
content = db.fetchone() 返回一條數據的查詢的結果
print(content)
# 函數調用
Obtain_one_date()sql = '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.創建數據庫連接對象
cou = mysql_db1()
2.創建游標
with cou.cursor() as cu: cu.execute(sql) 使用execute方法進行查詢語句 commt = cu.fetchone() 返回一條數據的查詢的結果 print(commt) # 函數調用 mysql_db1()
關于“python上下文管理器協議怎么實現”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“python上下文管理器協議怎么實現”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。