简体   繁体   English

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

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

I'm a noob with Python, but I've written an auto-close function like this.. 我是Python的菜鸟,但我写了一个这样的自动关闭函数..

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

I have three classes that have a Close() method that this function can be used with. 我有三个类有一个Close()方法,可以使用此函数。 Is this the most Pythonic solution? 这是最恐怖的解决方案吗? Should I be doing something in the classes themselves instead? 我应该自己在课堂上做些什么呢?

Most pythonic solution is to define methods __enter__ and __exit__ methods in your class: 大多数__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()

And using: 并使用:

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

Methods __enter__ and __exit__ will be implicitly called when entering and leaving blocks with . 方法__enter____exit__将进入和离开块时被隐式调用with Also note that __exit__ allows you to catch exception which raised inside the block with . 还要注意的是__exit__让你赶上了块内引发的异常with

Function contextlib.closing is typically used for those classes that do not explicitly define the methods __enter__ and __exit__ (but have a method close ). 函数contextlib.closing通常用于那些未明确定义方法__enter____exit__ (但方法close )的类。 If you define your own classes, much better way is to define these methods. 如果您定义自己的类,更好的方法是定义这些方法。

What you're doing looks totally fine and Pythonic. 你正在做的事情看起来很完美和Pythonic。 Although, the contextlib standard library already has something similar, but you'll have to rename your Close methods to close . 虽然, contextlib标准库已经有类似的东西,但您必须重命名Close方法才能close

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

I would recommend using this instead. 我建议改用它。 After all, the recommended naming convention for Python methods is all_lowercase_with_underscores . 毕竟,Python方法的推荐命名约定是all_lowercase_with_underscores

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

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