gpt4 book ai didi

python - 异常类

转载 作者:太空狗 更新时间:2023-10-30 00:40:43 25 4
gpt4 key购买 nike

我正在阅读 python 中的异常文档:-( https://docs.python.org/2/tutorial/classes.html#exceptions-are-classes-too )

我似乎无法找到这段代码是如何工作的

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

类里面的“pass”是什么意思?只需查看文档,我所能得到的就是创建所有类的对象(对象创建顺序:- B、C 和 D)并在它们的名称中引发异常,如果这是顺序,那么它解释了输出 B、C ,D.

但是如果我们用 except D 替换 excpet B ,整个输出就会改变。

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 C:
print "C"
except D:
print "D"

输出:-

B
B
B

现在这让我头晕目眩:/

“except”的顺序如何改变输出?

我知道我在文档中遗漏了一些东西,可能是因为它不是很清楚 :(

最佳答案

由于CDB的子类,它们都被except B子句捕获。捕获异常时,您需要始终从最具体到最不具体的顺序列出 except 子句,因为您的异常会被第一个适用的子句捕获。

来自documentation (强调我的):

The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.

pass 语句用于需要语句但不需要其他语句的地方。 class 语句不能有空主体,但通常最好改用文档字符串。

class B:
"""An exception that signals an error occurred"""

在句法上,文档字符串满足了在 class 语句主体中的语句的需要,但也提供了额外的信息。

关于python - 异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23657545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com