考慮下面的示例類中的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