簡體   English   中英

銷毀 class 的 object python

[英]destroy object of class python

嗨,如果滿足 if 語句的條件(在一段時間內),我正在嘗試銷毀 class object

global variablecheck

class 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?


這樣想:你要求 class 使用內部方法自毀,這有點像試圖吃掉自己的嘴。

幸運的是,Python 具有垃圾回收功能,這意味着一旦 scope 的所有引用都消失,您的 class 將自動銷毀。

如果你需要在實例被銷毀時做一些特定的事情,你仍然可以重寫__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...") 

現在,嘗試在本地 scope(例如函數)中實例化此 class:

def make_a_suicidal_class():
    my_suicidal_class = SelfDestruct()
    for i in range(5):
        my_suicidal_class.do_stuff()
    return None

在這里,object 的生命周期受 function 的約束。這意味着它會在調用完成后自動銷毀。 因此 output 應該是這樣的:

>>> 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!"
>>>

如果您的 class 是在全局 scope 中實例化的,那么在您的程序結束之前它不會被銷毀。

另外,應該注意手動調用__del__()析構函數並不會真正銷毀 object。這樣做:

foo = SelfDestruct()
foo.__del__()
foo.do_stuff()

結果是這個 output:

"Hi! I'm being instanciated!"
"I'm being automatically destroyed. Goodbye!"
"I'm doing some stuff..."

因此,實例仍然有一個脈沖......如果你真的需要防止實例在當前scope中再次被引用,你必須調用del foo來這樣做。

盡管如前所述,Python 實際上引用計數類和變量。 因此,如果您的 class object 被用於其他地方,則調用del foo實際上不會從 memory 中釋放它。

這是 python 文檔中的詳盡解釋https://docs.python.org/2.5/ref/customization.html

“del x”不直接調用 x。 del ()——前者將x的引用計數減1,后者僅在x的引用計數為零時調用。

長話短說:別想了。 讓python處理memory管理。 垃圾收集的全部意義在於不再擔心變量的生命周期!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM