[Tutor] Deleting an object

Hugo Arts hugo.yoshi at gmail.com
Sun Jan 29 16:36:33 CET 2012


On Sun, Jan 29, 2012 at 4:14 PM, George Nyoro <geonyoro at gmail.com> wrote:
> Hi all,
>
>        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?
>

__getattribute__ is the closest you'll get to that, e.g. like the
class below. A complete implementation is impossible, since language
builtins bypass even the __getattribute__ method, but as long as you
do not use them you should be fine:

class Table(object):
    def __init__(self):
        self.deleted = False

    def __getattribute__(self, attr):
        if object.__getattribute__(self, 'deleted'):
            raise AttributeError("this object has been deleted")
        return object.__getattribute__(self, attr)

    def __len__(self):
        return 10

    def delete(self):
        self.deleted = True

>>> # the object is still alive, we can access stuff easily
>>> t = Table()
>>> t.deleted
False
>>> t.__len__()
10
>>> t.delete()
>>> # now we cant access anything anymore without raising an error
>>> t.deleted

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    t.deleted
  File "C:\Users\hugo\Downloads\test.py", line 7, in __getattribute__
    raise AttributeError("this object has been deleted")
AttributeError: this object has been deleted
>>> t.__len__()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    t.__len__()
  File "C:\Users\hugo\Downloads\test.py", line 7, in __getattribute__
    raise AttributeError("this object has been deleted")
AttributeError: this object has been deleted
>>> # unfortunately, the python internals can still access your methods, so len() and things like operators will still work. There is no way around this
>>> len(t)
10
>>>

Of course this method can easily be adapted to restrict access only to
certain methods/attributes.

HTH,
Hugo


More information about the Tutor mailing list