销毁python类的对象

2024-10-01 17:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,如果满足if语句的条件(在一段时间内),我正在尝试销毁一个类对象

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?



Tags: theselfifobjectisdefthismethod
1条回答
网友
1楼 · 发布于 2024-10-01 17:36:19

这样想:你要求一个类使用一个内部方法进行自毁,这有点像试图吃掉你自己的嘴

幸运的是,Python具有垃圾收集功能,这意味着一旦类的所有引用都超出范围,它就会自动销毁

如果您需要在实例被销毁时执行特定的操作,您仍然可以重写__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...") 

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

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!"
>>>

如果类在全局作用域中实例化,则在程序结束之前不会销毁它

另外,应该注意的是,手动调用__del__()析构函数实际上并不销毁对象。这样做:

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

结果如下:

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

因此,实例仍然有一个脉冲。。。如果确实需要防止实例在当前作用域中再次被引用,则必须调用del foo来执行此操作

尽管如前所述,Python实际上引用了类和变量。因此,如果您的类对象用于elsewere,那么调用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来处理内存管理。垃圾收集的全部目的就是不再担心变量的寿命

相关问题 更多 >

    热门问题