亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

銷毀類python的對象

銷毀類python的對象

叮當貓咪 2023-06-13 19:15:18
如果滿足 if 語句的條件(在一段時間內),我正在嘗試銷毀一個類對象global variablecheckclass createobject:        def __init__(self,userinput):             self.userinput = input             self.method()                 def method(self):             while True:                if self.userinput == variablecheck                     print('the object created using this class is still alive')                                                  else:                    print('user object created using class(createobject) is dead')                    #what code can i put here to delete the object of this class?
查看完整描述

1 回答

?
largeQ

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處理內存管理。垃圾收集的全部意義在于不再擔心變量的生命周期!


查看完整回答
反對 回復 2023-06-13
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號