6

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?


coderoftheday
  • 1,987
  • 4
  • 7
  • 21
  • You cannot manually destroy objects in Python, Python uses automatic memory management. When an object is no longer referenced, it is free to be garbage collected, in CPython, which uses reference counting, when a reference count reaches zero, an object is reclaimed immediately. – juanpa.arrivillaga Aug 21 '20 at 10:30
  • so if i create another object of this class, the current object will destroy itself? – coderoftheday Aug 21 '20 at 10:32
  • Can we make reference count zero intentionally? just curious.. – sam Aug 21 '20 at 10:34
  • No. It won't. Again, objects are effectively destroyed (in CPython, this is how it works, but it isnt a language guarantee) when they are no longer referenced. – juanpa.arrivillaga Aug 21 '20 at 10:34
  • 1
    @sam in some cases. `x = Foo(); del x` removes the only reference to the object created by `Foo()`. However, it isn't always so straight forward. You cannot directly manipulate the reference count (well, almost anything is possible if you try hard enough, but that is a recipe for really bad things) – juanpa.arrivillaga Aug 21 '20 at 10:35
  • what do you mean by no longer referenced? wont it always be referenced since its a while loop? or maybe should i put 'return' to stop the function – coderoftheday Aug 21 '20 at 10:35
  • Makes sense.. @coderoftheday what is the actual requirement? why do you want to delete the object? Can it be handled by some other way like say an attribute "is_active" – sam Aug 21 '20 at 10:36
  • @coderoftheday there will **always** exist a reference to that object if your method is being executed, regardless of the loop, since the method object references the object internally. – juanpa.arrivillaga Aug 21 '20 at 10:37
  • basically every time a button is pressed, a new thread of class(createobject) is created, and in this class i run beautifulsoup and selenium – coderoftheday Aug 21 '20 at 10:38
  • It's quite unclear what you are trying to achieve, but you cannot delete any `createobject` instance while any of it's methods is running. – Maurice Meyer Aug 21 '20 at 10:47
  • How can you delete an object within a class??? – Sanmitha Sadhishkumar Aug 21 '20 at 13:06

1 Answers1

21

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!

Oneiros
  • 291
  • 3
  • 6
  • 1
    bear with me in trying to understand this, thank you though – coderoftheday Aug 21 '20 at 15:27
  • 2
    Cheers! Sorry if my explanation was not clear enough. – Oneiros Aug 21 '20 at 15:42
  • 1
    noo its very clear!!, I just need to tell my brain to understand. – coderoftheday Aug 21 '20 at 15:43
  • So what if I wanted a button just to kill the class even if its running ? – coderoftheday Sep 04 '20 at 07:34
  • Depends on your implementation but from what I've gathered, a new instance of your class gets created in a separate thread every every time a button is pressed. If this is a desired behaviour, then the following post could be of help: https://stackoverflow.com/questions/28127862/python-pyside-how-can-i-destroy-a-terminated-thread-object – Oneiros Sep 07 '20 at 16:47