From Zen of Python:
Explicit is better than implicit.
显式的执行一段代码要比“隐含”的好。如果你在销毁实例时隐含的执行其他代码,可能会为其他程序员带来困扰。。
要保证一段代码在实例被销毁时一定执行,可以使用try..finally:
file = None # setup file
try:
file = open('myfile')
file.readlines() # do things with file
finally:
file.close() # do things after tearing down file
因为File类实现了enter和exit方法, with表达式可以更简洁的完成上面的功能:
with file = open("myfile"):
file.readlines() # do things with file
类似的,你也可以为你的类实现这两个方法,来使用with表达式,简洁的确保代码在实例销毁后执行。
Class Resource(object):
def enter(self):
"""Setup; Must return a Resource object."""
resource = Resource()
resource = preprocess(resource)
return resource
def __exit__(self, type, value, traceback):
"""Things you wanna do when the resource object tears done.
Any exception dearing the with block is through in here as (type, value, traceback)."""
cleanUp()
if name == "main":
with beer = Resource("Beer"):
drink(beer) # do things with resource
You're done here. Cheers!