可能重复:
What is the equivalent of the C# “using” block in 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()
答案 0 :(得分:5)
Python 2.6引入了with
语句,该语句在离开with
语句时提供对象的自动清理。我不知道IronPython库是否支持它,但它很自然。
具有权威答案的问题:What is the equivalent of the C# "using" block in IronPython?
答案 1 :(得分:1)
我认为您正在寻找with statement。更多信息here。
答案 2 :(得分:0)
如果我理解正确,看起来等同于with
语句。如果您的类定义了上下文管理器,那么它们将在with块后自动调用。
答案 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 statment(如果您的对象为 __ 输入 __ 并且 _ 退出 __ 方法)然后您的代码将如下所示:
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()
和 __ 退出 __ 方法中的StreamWriter
sw.Dispose()