Python中与C#的using语句等效的方法

10

可能重复:
C#“using”块在IronPython中的等效物是什么?

我正在编写一些使用一些可释放的.NET对象的IronPython,并想知道是否有一种很好的“pythonic”方法来做到这一点。目前,我有一堆finally语句(我想每个语句中都应该检查None - 或者如果构造函数失败,变量甚至不会存在吗?)

def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:                
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
        try:
            sw = StreamWriter(isfs)
            try:
                sw.Write(data)
            finally:
                sw.Dispose()
        finally:
            isfs.Dispose()
    finally:
        isf.Dispose()
4个回答

10

谢谢,这让我找到了这个问题:https://dev59.com/qHI-5IYBdhLWcg3woJ5I,这是我之前的搜索中没有发现的。 - Mark Heath

3

0

您的代码带有一些注释:

def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:                
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)

        try: # These try is useless....
            sw = StreamWriter(isfs)
            try:
                sw.Write(data)
            finally:
                sw.Dispose()
        finally: # Because next finally statement (isfs.Dispose) will be always executed
            isfs.Dispose()
    finally:
        isf.Dispose()

对于 StreamWrite,您可以使用 with 语句(如果您的对象具有 __enter__ 和 __exit__ 方法),那么您的代码将如下所示:
def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:                
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
        with StreamWriter(isfs) as sw:
            sw.Write(data)
    finally:
        isf.Dispose()

在他的__exit__方法中,StreamWriter有

sw.Dispose()

如果需要的话,您也可以使用IsolatedStorageFile类的with语句。 - ohe

0
如果我理解正确的话,它看起来相当于with语句。如果你的类定义了上下文管理器,它们将在with块之后自动调用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接