Re: [問題] 如何強制使用 with statement

看板Python作者 (←這人是超級笨蛋)時間8年前 (2015/12/21 23:02), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《ResolaQQ (ResolaQQ)》之銘言: : 直覺的想法是在 __enter__ 的時候加個變數,執行其他函數的時候檢查,像這樣 : class Test(object): : def __init__(self): : self._with_statement = False : def __enter__(self): : self._with_statement = True : def __exit__(self, type, value, traceback): : pass : def do_something(self): : assert(self._with_statement) : 如此一來,如果沒用到 with statement,執行任何函數都會出錯 : 但是這寫法怎麼看怎麼蠢,也有漏寫 assert 的可能 : 請問有沒有比較好的寫法,既可以做到使用者防呆也能做到開發者防呆? 我的想法和推文一樣, 沒有必要強迫使用者用 context manager 重點是文件要寫好, 如果使用者愛亂搞是他家的問題 記得為什麼 Python 沒有 private member, 也沒什麼人愛用雙底線 trick 嗎? We're all grown-ups here. :) 但如果你真的不想讓使用者以其他方法 access 這個 class 可以考慮用 non-global definition import contextlib @contextlib.contextmanager def get_something(): class Something(object): def do_something(self): print('do something') print('enter') yield Something() print('exit') >>> with get_something() as thing: ... thing.do_something() ... enter do something exit -- 作者 Linux (Windows) 看板 C_and_CPP 標題 [問題] 如何確認是否 free 對記憶體 時間 Fri Nov 2 00:14:03 2012

11/02 00:43,
valgrind, 但 windowns 版的沒試過XD
11/02 00:43

11/02 00:44,
linux 上那真的是不二選擇了
11/02 00:44

11/02 00:45,
我是用 Windows ....>"<
11/02 00:45
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.161.94.175 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1450710178.A.29F.html

12/22 00:17, , 1F
挺有道理,我好像把事情弄的太複雜了
12/22 00:17, 1F
文章代碼(AID): #1MU1IYAV (Python)
文章代碼(AID): #1MU1IYAV (Python)