一、with語句的好處
with語句的好處在於,它可以自動幫我們釋放上下文,就比如文件句柄的操作,
如果你不使用with語句操作,你要先open一個文件句柄,使用完畢后要close這個文件句柄,
而使用with語句后,退出with代碼塊的時候就會自動幫你釋放掉這個文件句柄。
場景使用:
網絡連接、數據庫連接、文件句柄、鎖
二、如何讓對象支持with語句
方法: 在創建類的時候,在內部實現__enter__方法,with語句一開始就會執行這個方法, 再實現__exit__方法,退出with代碼塊的時候會自動執行這個方法。 例子: class A: def __enter__(self): print('with語句開始') return self # 返回self就是把這個對象賦值給as后面的變量 def __exit__(self, exc_type, exc_val, exc_tb): print('with語句結束') with A() as f: print('IG牛批') print(f) print('IG真的牛批') 結果: with語句開始 IG牛批 <__main__.A object at 0x0000027B4D1596D8> with語句結束 IG真的牛批
# 使用with操作文件 class A(object): def __init__(self): self.f = None def __enter__(self): print('with語句開始') self.f = open('with測試.txt', encoding='utf8', mode='w') return self.f def __exit__(self, exc_type, exc_val, exc_tb): print('with語句結束') self.f.close() with A() as f: print('IG牛批') f.write('嘿嘿嘿') print('IG真的牛批')
三、使用with語句優化pymysql的操作
1、使用with語句連接pymysql數據庫基本操作
import pymysql class SQLManager(object): # 初始化實例的時候調用connect方法連接數據庫 def __init__(self): self.conn = None self.cursor = None self.connect() # 連接數據庫 def connect(self): self.conn = pymysql.connect( host='127.0.0.1', port=3306, database='mydb', user='root', password='123abc', charset='utf8' ) self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) # 關閉數據庫 def close(self): self.cursor.close() self.conn.close() # 進入with語句自動執行 def __enter__(self): return self # 退出with語句自動執行 def __exit__(self, exc_type, exc_val, exc_tb): self.close()
2、還可以在上面的基礎上實現pymysql的一些操作
class SQLManager(object): # 初始化實例方法 def __init__(self): self.conn = None self.cursor = None self.connect() # 連接數據庫 def connect(self): self.conn = pymysql.connect( host='127.0.0.1', port=3306, database='mydb', user='root', password='123abc', charset='utf8' ) self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) # 查詢多條數據sql是sql語句,args是sql語句的參數 def get_list(self, sql, args=None): self.cursor.execute(sql, args) result = self.cursor.fetchall() return result # 查詢單條數據 def get_one(self, sql, args=None): self.cursor.execute(sql, args) result = self.cursor.fetchone() return result # 執行單條SQL語句 def moddify(self, sql, args=None): self.cursor.execute(sql, args) self.conn.commit() # 執行多條SQL語句 def multi_modify(self, sql, args=None): self.cursor.executemany(sql, args) self.conn.commit() # 創建單條記錄的語句 def create(self, sql, args=None): self.cursor.execute(sql, args) self.conn.commit() last_id = self.cursor.lastrowid return last_id # 關閉數據庫cursor和連接 def close(self): self.cursor.close() self.conn.close() # 進入with語句自動執行 def __enter__(self): return self # 退出with語句塊自動執行 def __exit__(self, exc_type, exc_val, exc_tb): self.close()