destroy object of class python
Asked Answered
S

1

7

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?


Softshoe answered 21/8, 2020 at 10:27 Comment(11)
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.Pretense
so if i create another object of this class, the current object will destroy itself?Softshoe
Can we make reference count zero intentionally? just curious..Mycenaean
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.Pretense
@Mycenaean 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)Pretense
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 functionSoftshoe
Makes sense.. @Softshoe 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"Mycenaean
@Softshoe 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.Pretense
basically every time a button is pressed, a new thread of class(createobject) is created, and in this class i run beautifulsoup and seleniumSoftshoe
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.Baldric
How can you delete an object within a class???Pohai
G
26

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!

Gynaecocracy answered 21/8, 2020 at 11:46 Comment(5)
bear with me in trying to understand this, thank you thoughSoftshoe
Cheers! Sorry if my explanation was not clear enough.Gynaecocracy
noo its very clear!!, I just need to tell my brain to understand.Softshoe
So what if I wanted a button just to kill the class even if its running ?Softshoe
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: #28128362Gynaecocracy

© 2022 - 2024 — McMap. All rights reserved.