python注销一段代码_Python-python中如何才能确保实例在被销毁后一定能执行一段代码?...

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值