假设有一个程序,在运行时其中有几个对象。
程序结束时是否调用每个对象的 __del__ 方法?
如果是的话,我可以做这样的事情:
class Client:
__del__( self ):
disconnect_from_server()
有许多潜在的困难 http://docs.python.org/reference/datamodel.html#object.__del__与使用相关__del__
。
通常,没有必要,或者最好自己定义它。
相反,如果您希望对象在退出或异常时自行清理,请使用上下文管理器 http://docs.python.org/reference/datamodel.html#context-managers:
根据卡尔的评论:
class Client:
def __exit__(self,ext_type,exc_value,traceback):
self.disconnect_from_server()
with Client() as c:
...
原答案:
import contextlib
class Client:
...
@contextlib.contextmanager
def make_client():
c=Client()
yield c
c.disconnect_from_server()
with make_client() as c:
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)