繁体   English   中英

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

[英]What's the Pythonic way to write an auto-closing class?

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

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

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

大多数__enter__解决方案是在您的类中定义方法__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()

并使用:

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

方法__enter____exit__将进入和离开块时被隐式调用with 还要注意的是__exit__让你赶上了块内引发的异常with

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM