相当于C#的using语句的Python [英] Python equivalent to C#'s using statement

查看:101
本文介绍了相当于C#的using语句的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
等同于C#使用" ;在IronPython中阻止?

Possible Duplicate:
What is the equivalent of the C# “using” block in IronPython?

我正在使用一些一次性的.NET对象编写一些IronPython,并想知道这样做是否有一种不错的"pythonic"方式.当前,我有一堆的finally语句(我想每个语句也都应该检查None,或者如果构造函数失败,该变量甚至不存在吗?)

I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I suppose there should be checks for None in each of them too - or will the variable not even exist if the constructor fails?)

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()

推荐答案

Python 2.6引入了with语句,该语句可在对象离开with语句时自动清除它们.我不知道IronPython库是否支持它,但这很自然.

Python 2.6 introduced the with statement, which provides for automatic clean up of objects when they leave the with statement. I don't know if the IronPython libraries support it, but it would be a natural fit.

带有权威答案的重复问题:>什么等同于C#使用"在IronPython中阻止?

Dup question with authoritative answer: What is the equivalent of the C# "using" block in IronPython?

这篇关于相当于C#的using语句的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆