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!
x = Foo(); del x
removes the only reference to the object created byFoo()
. 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) – Pretensecreateobject
instance while any of it's methods is running. – Baldric