[Tutor] Deleting an object

Alan Gauld alan.gauld at btinternet.com
Sun Jan 29 19:05:59 CET 2012


On 29/01/12 15:14, George Nyoro wrote:

> data. Thing is, I want to provide a method where one can delete the
> object and then if the user tries using a variable to access a certain
> method or attributes, he gets an error. Let me give an example;

I assume you know about the built in del() function that deletes 
objects? It works on any kind of object.

If you need it to do sometjing fancy(like releasing resources say) you 
can define your own __del__() method that gets called by Python when the 
object is deleted - but you rarely need to do that in Python.

> class Table:
>    def delete_this(self):
>    def do_something(self):

> 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 = Table()
del(x)

now referencing x or any attribute or method will give a name error.
Here is an example using an int, but any kind of object works:

 >>> x = 42
 >>> x
42
 >>> del(x)
 >>> x
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
 >>>

If thats not what you want you need to come vback and explain what is 
different about your scenario.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list