<>我计划使用Hyyy <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">with</a>语句实现我的Python类中的C++类构造函数/析构函数。到目前为止,我只对文件IO使用这个语句,但我认为它对基于连接的通信任务也很有帮助,比如<a href="http://docs.python.org/library/socket.html" rel="nofollow">sockets</a>或{a3}。最终需要关闭的东西。在</p>
<p>在pep343(上面链接)中,<code>with</code>需要方法<code>__enter__</code>和{<cd3>},我对此的直接实现似乎如预期的那样工作。在</p>
<pre><code>class MyConnection:
def __init__(self):
pass
def __enter__(self):
print "constructor"
# TODO: open connections and stuff
# make the connection available in the with-block
return self
def __exit__(self, *args):
print "destructor"
# TODO: close connections and stuff
with MyConnection() as c:
# TODO: do something with c
pass
</code></pre>
<p>产生输出(如预期):</p>
^{pr2}$
<p>真的应该这么简单吗?除此之外还有什么要考虑的?为什么这么多的库(表面上)还缺少这个功能?我错过什么了吗?在</p>