作者uranusjr (←这人是超级笨蛋)
看板Python
标题Re: [问题] 如何强制使用 with statement
时间Mon Dec 21 23:02:55 2015
※ 引述《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
1F:→ akasan:valgrind, 但 windowns 版的没试过XD 11/02 00:43
2F:→ akasan:linux 上那真的是不二选择了 11/02 00:44
3F:→ Linux:我是用 Windows ....>"< 11/02 00:45
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 218.161.94.175
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1450710178.A.29F.html
4F:推 ResolaQQ: 挺有道理,我好像把事情弄的太复杂了 12/22 00:17