簡體   English   中英

對象不執行__del__

[英]object is not execute __del__

我試圖在打開新端口時從數組創建對象,並在關閉壁櫥時將其刪除。

#!/usr/bin/python
import thread
import psutil
import time
thelist = []

class connection:
     def __init__(self, name):
         self.name = name
         print "open van stream"  + str(self.name)

     def __del__(self):
         print "close van stream "

def contains(list, filter):
     for x in list:
         if filter(x):
             return True
     return False

if __name__ == '__main__':
     try:
         PROCNAME = "tvheadend"
         for proc in psutil.process_iter():
             if proc.name == PROCNAME:
                 process = proc
         if not process:
             print "not found tvheadend"
             exit()
         print "Found " + str(process)

         while(1):
             for list in process.get_connections(kind='udp'):

                 if not contains(thelist, lambda x: x.name == list.local_address[0]):
                    thelist.append(connection(list.local_address[0]))

             for list in thelist:
                 print thelist
                 if not contains(process.get_connections(kind='udp'), lambda x: x.local_address[0] == list.name):
                     thelist.remove(list)
                     print "removed"
             time.sleep(0.5)

     except SystemExit, KeyboardInterrupt:
         exit()

但是當我打開一個新的時,它只打印“關閉流”。 不,當我關閉一個。 使用“打印主題列表”功能,我可以看到該對象已從數組中刪除,但不打印“關閉流”

只要您仍然從list引用它,它就不會消失。

重新分配list它就消失了。

只有這樣,該對象的引用計數器才會降至0,然后會調用__del__

順便說一句,調用變量list是一個壞主意,因為它掩蓋了內置類型list

而且,順便說一句, __del__ 不應被依賴 相反,您應該考慮定義和使用上下文管理器。

編輯:上下文管理器在這里顯然是不可能的,但是您應該顯式地.close()它,而不是依賴於被調用的__del__()

暫無
暫無

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

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