gpt4 book ai didi

python - 对自定义 Exception 的 try/except 感到困惑

转载 作者:太空狗 更新时间:2023-10-29 19:35:53 25 4
gpt4 key购买 nike

我的代码:

class AError(Exception):
print 'error occur'
for i in range(3):
try:
print '---oo'
raise AError
except AError:
print 'get AError'
else:
print 'going on'
finally:
print 'finally'

当我运行上面的代码时,输​​出是这样的:

error occur
---oo
get AError
finally
---oo
get AError
finally
---oo
get AError
finally

我认为字符串"error occur"应该出现三次,比如"---oo",但它只出现了一次;为什么?

最佳答案

澄清Paul's answer ,这是一个简单的例子:

class Test(object):

print "Class being defined"

def __init__(self):
print "Instance being created"


for _ in range(3):
t = Test()

此输出将是:

Class being defined
Instance being created
Instance being created
Instance being created

class 定义内但在方法 definitition 之外的代码 仅在定义类时运行一次

如果您希望代码每当创建一个实例时运行,它应该在__init__ 实例方法(或者,偶尔, __new__ 类方法)。但是,请注意,如果您为子类定义 __init__,您应该确保它也调用父类(super class)的 __init__:

class AError(Exception):

def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs) # call the superclass
print 'error occur' # print your message

这确保子类支持父类(super class)的参数;在 Exception 的情况下,您可以例如传递错误信息:

>>> raise AError("Something went wrong.")
error occur # your message gets printed when the instance is created

Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
raise AError("Something went wrong.")
AError: Something went wrong. # the error message passes through to the traceback

有关 *args, **kwargs 语法的解释,如果您不熟悉它,请参阅例如What does ** (double star) and * (star) do for parameters? .您还可以使用 super 调用父类(super class)方法,参见例如Understanding Python super() with __init__() methods .

关于python - 对自定义 Exception 的 try/except 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26733648/

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