2015-01-21 120 views
-2

以下是我的代码:如何删除另一个模块创建的对象?

from ab import Ab 

class Xyz: 
    def __init__(): 
     self.a = Ab.get_unique_instance() 

这是get_unique_instance()功能是如何在ab.py

class Ab: 
    instance = [] 
    def get_unique_instance(): 
     if len(Ab.instance) == 0: 
      new_instance = Ab() 
      Ab.instance.append(new_instance) 
     return Ab.instance[0] 

规定这样做是为了确保只有一个抗体的实例是有史以来在那里。问题在于即使从类Xyz创建的对象超出范围时,Ab的实例仍在内存中。如何显式删除这个对象?

+0

如果你只想要一个,为什么'Ab.instance'列表?你可以'weakref'这个实例,所以当其他引用它的东西超出范围时,它就会被删除。 – jonrsharpe 2015-01-21 11:52:26

+0

你可以做'del self.a',但是如果你可以提供你正在测试的'Ab的例子还在记忆中'那么我们可以给出更好的答案 – Nilesh 2015-01-21 11:52:35

+0

你也可以看看这个[post](http:// stackoverflow.com/q/6760685/1982962)在Python中创建一个单身人士 – 2015-01-21 11:53:17

回答

2

这里是一个可能的实现,使用weakref,以确保只有外部引用(即Single._instance)对引用计数计数:

import weakref 

class Single(object): 

    _instance = None 

    def __init__(self): 
     print "I've been born" 

    def __del__(self): 
     print "I'm dying" 

    @classmethod 
    def get_instance(cls): 
     if cls._instance is not None and cls._instance() is not None: 
      return cls._instance() 
     instance = cls() 
     cls._instance = weakref.ref(instance) 
     return instance 

因此,你必须在最多一个Single时间,但如果所有引用都被删除(并且在下一次对类方法的调用中将创建一个新的引用),则可以不包含任何引用。在使用:

>>> a = Single.get_instance() 
I've been born 
>>> b = Single.get_instance() 
>>> a is b 
True 
>>> del a 
>>> del b 
I'm dying 
>>> c = Single.get_instance() 
I've been born 
>>> del c 
I'm dying 
相关问题