销毁 class python 的对象

destroy object of class python

你好,如果满足 if 语句的条件(在一段时间内)

,我正在尝试销毁一个 class 对象
global variablecheck

class createobject:
        def __init__(self,userinput):
             self.userinput = input
             self.method()
         
        def method(self):
             while True:
                if self.userinput == variablecheck
                     print('the object created using this class is still alive')
                
                 
                 else:
                    print('user object created using class(createobject) is dead')
                    #what code can i put here to delete the object of this class?


这样想:您是在使用内部方法请求 class 到 self-destruct,这有点像试图吃掉自己的嘴。

幸运的是,Python 具有垃圾收集功能,这意味着一旦所有引用超出范围,您的 class 将自动销毁。

如果你需要在实例被销毁时做一些特定的事情,你仍然可以覆盖 __del__() 这将 有点 像析构函数一样。这是一个愚蠢的例子:

class SelfDestruct:
    def __init__(self):
        print("Hi! I'm being instanciated!")
    
    def __del__(self):
        print("I'm being automatically destroyed. Goodbye!")

    def do_stuff(self):
        print("I'm doing some stuff...") 

现在,尝试在本地范围(例如函数)中实例化此 class:

def make_a_suicidal_class():
    my_suicidal_class = SelfDestruct()
    for i in range(5):
        my_suicidal_class.do_stuff()
    return None

在这里,对象的生命周期受函数约束。这意味着它会在调用完成后自动销毁。因此输出应该如下所示:

>>> make_suicidal_class()
"Hi! I'm being instanciated!"
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm being automatically destroyed. Goodbye!"
>>>

如果你的 class 是在全局范围内实例化的,那么在你的程序结束之前它不会被销毁。

此外,应该注意手动调用 __del__() 析构函数并不会真正销毁对象。这样做:

foo = SelfDestruct()
foo.__del__()
foo.do_stuff()

结果是这样的输出:

"Hi! I'm being instanciated!"
"I'm being automatically destroyed. Goodbye!"
"I'm doing some stuff..."

ergo,实例还是有脉搏的。。。如果真的需要防止实例在当前范围内再次被引用,就得调用del foo 这样做。

尽管如前所述,Python 实际上是 reference-counts classes 和变量。因此,如果您的 class 对象在别处被使用,调用 del foo 将不会真正从内存中释放它。

python 文档中有详尽的解释 https://docs.python.org/2.5/ref/customization.html

"del x" doesn't directly call x.del() -- the former decrements the reference count for x by one, and the latter is only called when x's reference count reaches zero.

长话短说:别想了!让 python 处理内存管理。垃圾收集的全部意义在于不再担心变量的生命周期!