[Tutor] Deleting an object
Peter Otten
__peter__ at web.de
Sun Jan 29 17:34:12 CET 2012
George Nyoro wrote:
> Last time I tried to post a question regarding this, I was asked to
> clarify. Okay so here it is. There is a class called Table and objects are
> just tables, you know, matrices, holding different types of 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;
>
> 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
>
>
> All clear?
>>> class Parrot:
... def hello(self):
... print("Hello")
... def delete_this(self):
... self.__class__ = DeadParrot
...
>>> class DeadParrot:
... def __getattr__(self, name):
... raise Exception("This parrot is no more")
...
>>> p = Parrot()
>>> p.hello()
Hello
>>> p.delete_this()
>>> p.hello()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __getattr__
Exception: This parrot is no more
But I don't think it's a good idea...
More information about the Tutor
mailing list