简体   繁体   中英

destroy object of class python

Hi i'm trying to destroy a class object if the condition of an if statement(inside a while is met)

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?


Think of it that way: you're asking a class to self-destruct using an inner method, which is kind of like trying to eat your own mouth.

Luckily for you, Python features garbage collection, meaning your class will be automatically destroyed once all of its references have gone out of scope.

If you need to do something specific when the instance is being destroyed, you can still override __del__() which will kinda act like a destructor. Here's a silly example:

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...") 

Now, try instanciating this class in a local scope (such as a function):

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

Here, the lifespan of the object is bound by the function. Meaning it'll be automatically destroyed once the call is completed. Thus the output should look like:

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

If your class was instanciated in a global scope, then it won't be destroyed until your program ends.

Also, it should be noted that manually calling the __del__() destructor does NOT actually destroy the object. Doing this:

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

Results is this output:

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

ergo , the instance still has a pulse... If you really need to prevent the instance from being referenced again in the current scope, you have to call del foo to do so.

Though as previously stated, Python actually reference-counts classes and variables. So if your class object is used elsewere, invoking del foo will not actually release it from memory.

Here's an exhaustive explanation in the python docs 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.

Long story short: Don't think about it. Let python deal with memory management. The whole point of garbage collection is to stop worrying about the lifespan of your variables!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM