繁体   English   中英

如何定义可以与with语句一起使用的Python类?

[英]How do I define a Python class that I can use with the with statement?

我知道StringIO就像一个文件对象,可以open('somefile.txt')你从open('somefile.txt')

现在我想使用带有with语句的StringIO

with StringIO('some string') as fh: # fh as in "file handle"
    data = [stuff from stuff in fh.read()]

但Python抱怨StringIO类型没有__exit__方法。 StringIO

class MyStringIO(StringIO):
    def __exit__(self):
        self.close()

我现在得到一个关于没有__enter__方法的例外。 如何定义__enter__方法? Python对可以与with语句一起使用的类有什么期望?

您需要编写上下文管理器 如果您不想编写整个协议,可以使用contextlib.contextmanager装饰器简化它。

只是举一个例子来说它是矫枉过正的,请使用contextlib,它更适用于生成器:

这是一个很好的有用的上下文管理器示例。 我在David Beazley的博客中找到了它:

http://dabeaz.blogspot.de/2010/02/context-manager-for-timing-benchmarks.html

并且只是稍微修改它以使用每个平台的最佳计时器,这是我在timeit模块中使用的技巧:

# benchmark.py
import timeit
class benchmark(object):
    from timeit import default_timer as timer
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        self.start = self.timer()
    def __exit__(self, ty, val, tb):
        end = self.timer()
        print("%s : %0.3f seconds" % (self.name, end-self.start))
        return False

现在,它为您提供了一个上下文管理器,您可以像这样使用:

with benchmark('algorithm 1'):
    ... (some computation)
with benchmark('other approach'):
    ... (some other computation)

并打印出你的输出。 我喜欢这个例子,想分享它。

您可以像使用__exit__一样定义__enter__方法。 这些是对象与with语句一起使用所需的两种方法,有关详细信息,请参阅方法。

暂无
暂无

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

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