什么是Pythonic编写自动关闭类的方法?

blu*_*dog 5 python

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

@contextmanager
def AutoClose(obj):
    try:
        yield obj
    finally:
        obj.Close()
Run Code Online (Sandbox Code Playgroud)

我有三个类有一个Close()方法,可以使用此函数.这是最恐怖的解决方案吗?我应该自己在课堂上做些什么呢?

def*_*fuz 9

大多数pythonic解决方案是在您的类中定义方法__enter____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()
Run Code Online (Sandbox Code Playgroud)

并使用:

with Foo('/path/to/file') as foo:
    # do something with foo
Run Code Online (Sandbox Code Playgroud)

进入和离开块时将隐式调用方法__enter__和方法.另请注意,允许您捕获块内引发的异常.__exit__with__exit__with

函数contextlib.closing通常用于不显式地定义的方法这些类__enter____exit__(但有一个方法close).如果您定义自己的类,更好的方法是定义这些方法.

  • 你的`__enter__`忽略返回一些有用的东西,例如`self`。我花了很长时间才找到问题所在。 (3认同)

tom*_*tom 8

你正在做的事情看起来很完美和Pythonic.虽然,contextlib标准库已经有类似的东西,但你必须重命名你的Close方法close.

import contextlib
with contextlib.closing(thing):
    print thing
Run Code Online (Sandbox Code Playgroud)

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