让对象支持with语句

复制代码
一、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语句优化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()
复制代码

 

转载于:https://www.cnblogs.com/yidashi110/p/10091991.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值