How to delete an instance of a class using a function?

84 Views Asked by At

I am looking for a way to create a method within a class that will delete that particular instance.

I know one way to do is by using del keyword but I want to make it user interaction based so that user can simply call the method and that instance will be deleted. How can I do that?

1

There are 1 best solutions below

0
On

@user2357112 mentioned how you cannot manually delete objects in Python, they are correct. Python objects are deleted when there are no more references to them. del removes the reference to an object and once that number of references goes down to zero, the garbage collector can reclaim the memory used by that object.

From Python:

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised...

del removes the reference to that instance of a class, if there are no other references to that instance elsewhere in your code, that reference count drops to zero, thereby allowing the garabage collector to reclaim the memory. The GC doesn't run immediately after every del statement, so once the GC runs again, it will reclaim your deleted instance.