免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2250 | 回复: 2
打印 上一主题 下一主题

新手请教 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-03-15 16:19 |只看该作者 |倒序浏览
我在学习python的时候,有个问题看不懂
请各位高手指教。
class B:
    pass
class C(B):
    pass
class D(C):
    pass

for c in [B,C,D]:
    try:
        raise c()
    except D:
        print 'D'
    except C:
        print 'C'
    except B:
        print 'B'

输出
B
C
D

若写成
class B:
    pass
class C(B):
    pass
class D(C):
    pass

for c in [B,C,D]:
    try:
        raise c()
    except B:
        print 'B'
    except D:
        print 'D'
    except C:
        print 'C'

输出
B
B
B


请问这该怎么解释?

论坛徽章:
0
2 [报告]
发表于 2006-03-15 16:53 |只看该作者
Python Manual里对try catch 语句执行的解释
The try statement works as follows.


First, the try clause (the statement(s) between the try and except keywords) is executed.

If no exception occurs, the except clause is skipped and execution of the try statement is finished.

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.


都输出B,我想是因为isinstance(C(),B)和isinstance(D(),B)都是True,所以第一个catch满足了就不再继续catch了。

[ 本帖最后由 wolfg 于 2006-3-15 17:00 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2006-03-15 19:34 |只看该作者
哦,我明白了,谢谢你!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP