anything went wrong.
如果BLOCK引发了异常,那么它会根据这个异常去调用__exit__(type, value, traceback)。
这个方法所返回的值同sys.exc_info()方法是相同的。这个返回值会告诉系统是不是再把
异常往上抛: false值表示再抛,True表示把它压下来。一般来说你不太需要去压制异常,
因为要是你在这里把异常压了下来,那些写with语句的人就永远也不知道这里还发生过异常了。
If BLOCK didn't raise an exception, the __exit__() method is still called,
but type, value, and traceback are all None.
如果BLOCK没有引发异常,with还是会调用__exit__()方法,只是这时type, value,
traceback都是None。
Let's think through an example. I won't present detailed code but will only
sketch the methods necessary for a database that supports transactions.
我们举一个例子。我不会给具体的代码,只是大致地划拉一下一个
支持transaction地数据库所必须提供的方法。
(For people unfamiliar with database terminology: a set of changes to
the database
are grouped into a transaction. Transactions can be either committed,
meaning that
all the changes are written into the database, or rolled back, meaning that the
changes are all discarded and the database is unchanged. See any
database textbook
for more information.)
(这段话是为那些不熟悉数据库的朋友准备的: 所谓transaction就是把一组对数据库的修改捆绑起来。
你可以commit一个transaction,也就是说把这些修改全部写入数据库;也可以roll back,
也就是说把这些修改全都扔掉。随便找本数据库的书都会比我这里讲的详细。)
Let's assume there's an object representing a database connection.
Our goal will be to let the user write code like this:
架设这里有一个表示database connection的对象。我们的目标是要让用户能这样写代码:
db_connection = DatabaseConnection()
with db_connection as cursor:
cursor.execute('insert into ...')
cursor.execute('delete from ...')
# ... more operations ...
The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
DatabaseConnection
that I'll assume:
如果block运行无误的话,这个transaction就算是commit了。只要有异常,我们就roll back。
下面是我所预想的这个DatabaseConnection的基本接口。
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | with 一个 对象 语句 这个 方法 异常 如果 可以 返回 |
注册
个人空间
