[Tutor] Deleting an object

Steven D'Aprano steve at pearwood.info
Sun Jan 29 16:59:12 CET 2012


George Nyoro wrote:

> class Table:
> def delete_this(self):
> #code to delete this object or assign it null or None
> pass
> def do_something(self):
> pass
> 
> x=Table()
> x.delete_this()
> 
> #at this point, I want such that if I try to use x I get some sort of error
> e.g.
> 
> x.do_something()
> 
> #Error: x is definitely not an object anymore


Instead of "x.delete_this()", why not just say "del x"? Why try to fight 
Python, instead of using the tools Python already gives you?


Objects cannot delete themselves, because they cannot know all the places they 
are referenced.

If you absolutely have to have something like x.delete_this, then try this:


class Table:
     def __init__(self):
         self.alive = True
     def delete_this(self):
         self.alive = False
     def do_something(self):
         if self.alive:
             print("Doing something.")
         else:
             raise TableError("object has been killed")

class TableError(RuntimeError):
     pass


-- 
Steven



More information about the Tutor mailing list