在为自己的类使用withstatement时需要注意哪些事项?

2024-06-16 11:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

<>我计划使用Hyyy with语句实现我的Python类中的C++类构造函数/析构函数。到目前为止,我只对文件IO使用这个语句,但我认为它对基于连接的通信任务也很有帮助,比如sockets或{a3}。最终需要关闭的东西。在

在pep343(上面链接)中,with需要方法__enter__和{},我对此的直接实现似乎如预期的那样工作。在

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

产生输出(如预期):

^{pr2}$

真的应该这么简单吗?除此之外还有什么要考虑的?为什么这么多的库(表面上)还缺少这个功能?我错过什么了吗?在


Tags: andtheselfdefwithpass语句connections
2条回答

我在尝试在库中实现'with'功能时遇到的一个问题是找到一种处理失败异常的优雅方法。考虑到以下因素:

class open_file_for_read(object):
    def __init__(self):
        self.filename = "./does_not_exist.txt"
        self.fileobj = None

    def __enter__(self):
        print("Opening file %s for read" % self.filename)
        self.fileobj = open(name=self.filename, mode='r')
        return self.fileobj

    def __exit__(self, type, value, traceback):
        self.fileobj.close()


with open_file_for_read() as fh:
    for li in fh.readlines():
        print(li)

如何处理不可避免的“IOError:[Errno 2]没有这样的文件或目录:'。/不_存在.txt'例外?总是有“尝试/排除”的方法

^{pr2}$

这种直接的方法是可行的,但我认为它有损于使用'with'结构的简单性。也许有人有更优雅的解决方案?在

这个问题的解决方法更多的是一个问题而不是一个答案,但这是我在尝试实现“with”时遇到的问题之一。在

(a)就这么简单

(b)另一种方法是decorator函数,它修饰函数(和类,但不适用于本用例),还允许在包装函数之前和之后调用代码。这些似乎更为常见。在

(c)我不认为你遗漏了什么。在

相关问题 更多 >