【问题标题】:What's the Pythonic way to write an auto-closing class?编写自动关闭类的 Pythonic 方式是什么?
【发布时间】:2013-08-12 06:33:09
【问题描述】:

我是 Python 的菜鸟,但我写了一个像这样的自动关闭函数..

@contextmanager
def AutoClose(obj):
    try:
        yield obj
    finally:
        obj.Close()

我有三个类,它们有一个可以与此函数一起使用的 Close() 方法。这是最 Pythonic 的解决方案吗?我应该在课堂上自己做点什么吗?

【问题讨论】:

  • 这看起来不错。你也可以在你的类中使用析构函数。
  • 我会避免使用析构函数(即__del__)。很难推断何时/是否被调用。在此处查看接受的答案:stackoverflow.com/questions/1935153/…

标签: python


【解决方案1】:

您所做的一切看起来都很好,而且符合 Python 风格。虽然contextlib 标准库已经有类似的东西,但你必须将你的Close 方法重命名为close

import contextlib
with contextlib.closing(thing):
    print thing

我建议改用这个。毕竟,Python 方法的推荐命名约定是all_lowercase_with_underscores

【讨论】:

  • 请注意,'bluedog' 可能还必须将他(或她)的 .Close() 方法重命名为 .close() 才能使用 contextlib.closing()(除非我弄错了)。
  • 我必须在当前情况下保留 Close() 方法,但我可能会添加一个名为 close() 的别名,以便可以使用标准的 contextlib.closure 函数。
【解决方案2】:

大多数pythonic解决方案是在你的类中定义方法__enter__ and __exit__方法:

class Foo(object):
     def __init__(self, filename):
         self.filename = filename

     def __enter__(self):
         self.fd = open(self.filename)

     def __exit__(self, exc_type, exc_value, traceback):
         self.fd.close()

并使用:

with Foo('/path/to/file') as foo:
    # do something with foo

方法__enter____exit__ 将在进入和离开块with 时被隐式调用。另请注意,__exit__ 允许您捕获在块 with 内引发的异常。

函数contextlib.closing 通常用于那些没有明确定义方法__enter____exit__(但有方法close)的类。如果您定义自己的类,更好的方法是定义这些方法。

【讨论】:

  • +1 - 这是一个同样好的答案 IMO。我选择了@tom 的答案,因为这是我将在这种情况下使用的解决方案。这三个特定的类都有一个 Close() 方法并且不需要 __enter__,因此单个 auto_close 函数可以用于所有三个类,而无需触及类本身。
猜你喜欢
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 2012-09-12
  • 2010-12-13
相关资源
最近更新 更多