python中用with关键字来实现上下文管理器.

例子

with open(r'somefileName') as somefile:
     for line in somefile:
            print line

with 语句的语法


with <context_expression> [as <target>]:
     <with-body>
     

什么语句可以作为<context_expression>, <target>变量是在哪里定义的呢?

  • <context_expression>应该返回一个上下文管理器,所谓上下文管理器就是任何一个实现了 __enter__(self) ,和__exit__(self, *unused)方法的class的实例.

  • __enter__(self)对象中返回的内容会被赋值给<target>变量

直接用类进行构造的构造函数

class PypixContextManagerDemo:
    def __enter__(self):
        print 'Entering the block'
    def __exit__(self, *unused):
        print 'Exiting the block'
with PypixContextManagerDemo():
    print 'In the block'

也可以用工厂方法建立

以MySQLdb为例,通常是调用MySQLdb.Connect方法建立的Connection的实例的.而在MySQLdb中Connect方法是这样实现的.

def Connect(*args, **kwargs):
    """Factory function for connections.Connection."""
    from MySQLdb.connections import Connection
    return Connection(*args, **kwargs)

而在Connection类中实现了__enter__(self) ,和__exit__(self, *unused)方法

class Connection(_mysql.connection):
.....................
    def __enter__(self):
            if self.get_autocommit():
                self.query("BEGIN")
            return self.cursor()
            
    def __exit__(self, exc, value, tb):
        if exc:
            self.rollback()
        else:
            self.commit()

注意__enter__方法直接返回了cursor对象,因此as后跟的就是一个cursor对象

with MySQLdb.connect(kwargs=Mysqldb_kwargs) as ins_cursor:
        ins_cursor.execute('select * from user')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值