[問題] 如何強制使用 with statement
直覺的想法是在 __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 的可能
請問有沒有比較好的寫法,既可以做到使用者防呆也能做到開發者防呆?
--
放著養蚊子的部落格 http://resolaqq.blogspot.tw
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.165.73.83
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1450692859.A.86C.html
推
12/21 22:24, , 1F
12/21 22:24, 1F
→
12/21 22:25, , 2F
12/21 22:25, 2F
→
12/21 22:25, , 3F
12/21 22:25, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):