[問題] class的__del__

看板Python作者 (nahgnimiast)時間5年前 (2019/12/29 13:19), 編輯推噓1(105)
留言6則, 5人參與, 6年前最新討論串1/1
我有一個class,是全域變數。 在__del__時,會使用一些import進來的模組 比如csv或是configparser把值寫回檔案 ------------------------------------- class CONFIG(object): def __init__(self): .... def __del__(self): ... _CONFIG = CONFIG() ------------------------------------- 我本來想說在python結束時,會觸發__del__,但是 碰到import進來的模組會報一些奇怪的錯誤,比如說 open函式找不到,後來亂試,在程式結束前強制刪除(見下面) ------------------------------------- del _CONFIG ------------------------------------- 結果問題似乎就消失了,請問__del__是不是在 python結束時,可能會不能正常使用module?一般會怎麼 處理這種情況? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.136.82.128 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1577596782.A.1D4.html

12/29 13:28, 5年前 , 1F
上網查了一下,__del__好像有很多限制,不能亂用
12/29 13:28, 1F

12/29 23:01, 5年前 , 2F
你要的應該是with...as,del不是這樣用的
12/29 23:01, 2F

12/30 03:26, 5年前 , 3F
at exit?
12/30 03:26, 3F

12/30 03:27, 5年前 , 4F
atexit 沒空格
12/30 03:27, 4F

12/31 04:11, 5年前 , 5F
這不是C++ destructor沒辦法讓你做RAII
12/31 04:11, 5F

01/03 13:43, 6年前 , 6F
__del__ 除了 del 之外不一定保證觸發,要看有沒有 GC
01/03 13:43, 6F
文章代碼(AID): #1U23Tk7K (Python)
文章代碼(AID): #1U23Tk7K (Python)