gpt4 book ai didi

python - 有没有办法像C#的 "with"一样使用Python "using"语句

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:01 25 4
gpt4 key购买 nike

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

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

class ForUseInWith(IDisposableLike):
#something here
pass

并像这样使用它:

with ForUseInWith() as disposable:
#something here
pass

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

最佳答案

这很容易做到,你只需要在你的类中有一个 __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__ 方法。这种结构最适用于简单的类,也有能够被处置的要求,或者是一次性的过程,不需要坚持或有复杂的处置

关于python - 有没有办法像C#的 "with"一样使用Python "using"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com