如何强制删除python对象?

如何强制删除python对象?,第1张

如何强制删除python对象

关闭资源的方法是上下文管理器,又称

with
语句:

class Foo(object):  def __init__(self):    self.bar = None  def __enter__(self):    if self.bar != 'open':      print 'opening the bar'      self.bar = 'open'    return self # this is bound to the `as` part  def close(self):    if self.bar != 'closed':      print 'closing the bar'      self.bar = 'close'  def __exit__(self, *err):    self.close()if __name__ == '__main__':  with Foo() as foo:    print foo, foo.bar

输出:

opening the bar<__main__.Foo object at 0x17079d0> openclosing the bar

2)当它们的引用计数为0时,Python的对象将被删除。在您的示例中,

delfoo
removes删除了最后一个引用,因此
__del__
即刻被调用。GC不参与其中。

class Foo(object):    def __del__(self):        print "deling", selfif __name__ == '__main__':    import gc    gc.disable() # no gc    f = Foo()    print "before"    del f # f gets deleted right away    print "after"

输出:

beforedeling <__main__.Foo object at 0xc49690>after

gc
没有任何与删除您和其他大多数的对象。由于自引用或循环引用而无法进行简单的引用计数时,可以在此进行清理:

class Foo(object):    def __init__(self, other=None):        # make a circular reference        self.link = other        if other is not None: other.link = self    def __del__(self):        print "deling", selfif __name__ == '__main__':    import gc    gc.disable()       f = Foo(Foo())    print "before"    del f # nothing gets deleted here    print "after"    gc.collect()    print gc.garbage # The GC knows the two Foos are garbage, but won't delete          # them because they have a __del__ method    print "after gc"    # break up the cycle and delete the reference from gc.garbage    del gc.garbage[0].link, gc.garbage[:]    print "done"

输出:

beforeafter[<__main__.Foo object at 0x22ed8d0>, <__main__.Foo object at 0x22ed950>]after gcdeling <__main__.Foo object at 0x22ed950>deling <__main__.Foo object at 0x22ed8d0>done

3)让我们看看:

class Foo(object):    def __init__(self):        raise Exception    def __del__(self):        print "deling", selfif __name__ == '__main__':    f = Foo()

给出:

Traceback (most recent call last):  File "asd.py", line 10, in <module>    f = Foo()  File "asd.py", line 4, in __init__    raise ExceptionExceptiondeling <__main__.Foo object at 0xa3a910>

使用创建对象,

__new__
然后将其传递给
__init__
as
self
。在中出现异常后
__init__
,该对象通常将没有名称(即该
f=
部件未运行),因此其引用计数为0。这意味着该对象将被正常删除并被
__del__
调用。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5507878.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存