1 回答

TA貢獻2039條經驗 獲得超8個贊
這樣想:你要求一個類使用內部方法自毀,這有點像試圖吃掉自己的嘴。
幸運的是,Python 具有垃圾收集功能,這意味著一旦所有引用都超出范圍,您的類將自動銷毀。
如果您需要在實例被銷毀時做一些特定的事情,您仍然可以覆蓋__del__()它,這有點像析構函數。這是一個愚蠢的例子:
class SelfDestruct:
def __init__(self):
print("Hi! I'm being instanciated!")
def __del__(self):
print("I'm being automatically destroyed. Goodbye!")
def do_stuff(self):
print("I'm doing some stuff...")
現在,嘗試在本地范圍(例如函數)中實例化此類:
def make_a_suicidal_class():
my_suicidal_class = SelfDestruct()
for i in range(5):
my_suicidal_class.do_stuff()
return None
在這里,對象的生命周期受函數約束。這意味著它會在調用完成后自動銷毀。因此輸出應該是這樣的:
>>> make_suicidal_class()
"Hi! I'm being instanciated!"
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm being automatically destroyed. Goodbye!"
>>>
如果你的類是在全局范圍內實例化的,那么在你的程序結束之前它不會被銷毀。
另外,應該注意手動調用__del__()析構函數并不會真正銷毀對象。這樣做:
foo = SelfDestruct()
foo.__del__()
foo.do_stuff()
結果是這個輸出:
"Hi! I'm being instanciated!"
"I'm being automatically destroyed. Goodbye!"
"I'm doing some stuff..."
因此,實例仍然有一個脈沖......如果你真的需要防止實例在當前范圍內再次被引用,你必須調用del foo這樣做。
盡管如前所述,Python 實際上對類和變量進行引用計數。因此,如果您的類對象在其他地方使用,調用del foo實際上不會從內存中釋放它。
這是 python 文檔中詳盡的解釋 https://docs.python.org/2.5/ref/customization.html
“del x”不直接調用 x。del ()——前者將x的引用計數減1,后者僅在x的引用計數為零時調用。
長話短說:別想了!讓python處理內存管理。垃圾收集的全部意義在于不再擔心變量的生命周期!
添加回答
舉報