1、with语句的好处 with语句的好处在于,它能够自动帮咱们释放上下文,就好比文件句柄的操做, 若是你不使用with语句操做,你要先open一个文件句柄,使用完毕后要close这个文件句柄, 而使用with语句后,退出with代码块的时候就会自动帮你释放掉这个文件句柄。 场景使用: 网络链接、数据库链接、文件句柄、锁 2、如何让对象支持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真的牛批 3、使用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()