How to force deletion of a python object?

前端 未结 4 1190
逝去的感伤
逝去的感伤 2020-11-30 19:36

I am curious about the details of __del__ in python, when and why it should be used and what it shouldn\'t be used for. I\'ve learned the hard way that it is n

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 20:10

    Perhaps you are looking for a context manager?

    >>> class Foo(object):
    ...   def __init__(self):
    ...     self.bar = None
    ...   def __enter__(self):
    ...     if self.bar != 'open':
    ...       print 'opening the bar'
    ...       self.bar = 'open'
    ...   def __exit__(self, type_, value, traceback):
    ...     if self.bar != 'closed':
    ...       print 'closing the bar', type_, value, traceback
    ...       self.bar = 'close'
    ... 
    >>> 
    >>> with Foo() as f:
    ...     # oh no something crashes the program
    ...     sys.exit(0)
    ... 
    opening the bar
    closing the bar  0 
    

提交回复
热议问题