【问题标题】:Is there a way to use the Python "with" statement like the "using" of C#有没有办法像 C# 的“使用”一样使用 Python “with”语句
【发布时间】:2013-12-12 22:51:27
【问题描述】:

我正在阅读this question,我想到我也需要它,但在 Python 中。 所以我想知道是否有办法使用 Python 中的 with 语句来做到这一点。

基本上我想要的是 Python 中的某种 IDisposable (C#) 类比。我知道,肯定会有所不同,我认为是这样的:

class ForUseInWith(IDisposableLike):
    #something here
    pass

并像这样使用它:

with ForUseInWith() as disposable:
    #something here
    pass

目前我正在研究如何做到这一点,研究python referencePEP 343,如果我设法做一个好的解决方案和一个聪明的例子,我会在这里发布答案。但顺便说一句,也许你可以帮助我。

【问题讨论】:

    标签: python


    【解决方案1】:

    这很容易做到,你只需要在你的类中有一个__enter__ 和一个__exit__ 方法。

    示例:

    class ForUseInWith(object):
    
        def test(self):
            print 'works!'
    
        def __enter__(self):
            return self
    
        def __exit__(self, *args, **kwargs):
            pass
    

    使用它:

    >>> with ForUseInWith() as disposable:
        disposable.test()
    
    works!
    

    扩展它:

    当然,您可以拥有一个接收参数的__init__ 方法(就像open() 一样),您还可以在__exit__ 方法中包含处理错误/异常的方法。这种结构最好用于简单的类,这些类也有要求可以被处置,或者是一次性的进程,不需要留下来或有复杂的处置

    【讨论】:

    • 只是我正在寻找的示例。而且我在我的帖子中发现了一个错误。
    猜你喜欢
    • 2023-01-07
    • 1970-01-01
    • 2011-01-23
    • 2010-10-21
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多