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')
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论