考虑下面的示例类中的Python:Python的析构函数失败构造
class MyClass:
def __init__(self, obj):
self._obj = obj
def __del__(self):
if self._obj:
print(self._obj)
在测试套件
,我想检查时调用构造函数不带参数抛出一个异常,即:
c = MyClass()
有了这个,我得到预期的异常从构造函数:
Traceback (most recent call last):
File ".../example.py", line 9, in <module>
c = MyClass()
TypeError: __init__() missing 1 required positional argument: 'obj'
然而,析构函数也将失败与消息:
Exception ignored in: <bound method MyClass.__del__ of <__main__.MyClass object at 0x0000023D1211CD30>>
Traceback (most recent call last):
File ".../example.py", line 6, in __del__
if self._obj:
AttributeError: 'MyClass' object has no attribute '_obj'
据推测,这是因为构造函数没有被调用,因为有一种说法缺少的,因此永远不会创建的属性。
解决这个问题的正确方法是什么?
你有没有一个抽象的例子?如果你真的想要安全,可以使用'getattr'或'try'属性访问。 – jonrsharpe
Python没有析构函数。它确实有终结者。通常,做事的正确方法是避免完全使用它们。 –
值得注意的是'__del__'中产生的异常被忽略。 – Blckknght