with open(r\'somefileName\') as somefile:
for line in somefile:
print line
with 语句的语法
with [as ]:
,
变量是在哪里定义的呢? __enter__(self)
,和__exit__(self, *unused)
方法的class
的实例.
在 __enter__(self)
对象中返回的内容会被赋值给
变量
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\')
上一篇:Python基础教程
下一篇:如何在python中import