gpt4 book ai didi

python - 即使 `__init__()` 引发异常也使用对象?

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:30 26 4
gpt4 key购买 nike

我所处的情况是类 __init__ 方法的一些微不足道的重要部分可能会引发异常。在那种情况下,我想显示一条错误消息,但继续使用该实例。

一个非常基本的例子:

class something(object):
def __init__(self):
do_something_important()
raise IrrelevantException()

def do_something_useful(self):
pass

try:
that_thing = something()
except IrrelevantException:
print("Something less important failed.")

that_thing.do_something_useful()

但是,最后一行不起作用,因为 that_thing 没有定义。奇怪的是,我可以发誓我以前做过这样的事情,而且效果很好。我什至想过如何阻止人们使用这样一个未完成的实例,因为我发现即使在出现错误的情况下它也会被创建。现在我想使用它,但它不起作用。嗯……?!?

PS: something 是我自己写的,所以我控制一切。

最佳答案

您可以通过调用 object.__new__() 来创建对象来完成此操作。然后调用 __init__() 来创建对象。

这将执行所有可能的代码。

class IrrelevantException(Exception):
"""This is not important, keep executing."""
pass

class something(object):
def __init__(self):
print("Doing important stuff.")
raise IrrelevantException()

def do_something_useful(self):
print("Now this is useful.")

that_thing = object.__new__(something) # Create the object, does not call __init__
try:
that_thing.__init__() # Now run __init__
except IrrelevantException:
print("Something less important failed.")

that_thing.do_something_useful() # And everything that __init__ could do is done.

编辑,正如@abarnert 指出的那样。此代码假定 __init__() 已定义,但 __new__() 未定义。

现在如果可以假设__new__()不会出错,它可以替换代码中的object.__new__()

但是,如果 object.__new__() 中出现错误,则无法既创建实例又应用 __new__() 中的操作给它。

这是因为 __new__() 返回实例,而 __init__() 操作实例。 (当你调用 something() 时,默认的 __new__() 函数实际上调用了 __init__() 然后悄悄地返回实例。)

所以这段代码的最健壮的版本是:

class IrrelevantException(Exception):
"""This is not important, keep executing."""
pass

class something(object):
def __init__(self):
print("Doing important stuff.")
raise IrrelevantException()

def do_something_useful(self):
print("Now this is useful.")

try:
that_thing = something.__new__(something) # Create the object, does not call __init__
except IrrelevantException:
# Well, just create the object without calling cls.__new__()
that_thing = object.__new__(something)
try:
that_thing.__init__() # Now run __init__
except IrrelevantException:
print("Something less important failed.")

that_thing.do_something_useful()

所以,同时这两个都回答了这个问题,后一个也应该在 __new__() 有错误的情况下(公认的罕见)有帮助,但这不会停止 do_something_useful () 从工作开始。

关于python - 即使 `__init__()` 引发异常也使用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51254859/

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