Re: [問題] 如何強制使用 with statement
※ 引述《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,
11/02 00:43
→
11/02 00:44,
11/02 00:44
→
11/02 00:45,
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
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):