object reincarnation

Carl Banks pavlovevidence at gmail.com
Thu Jun 11 05:11:04 EDT 2009


On Jun 10, 12:34 pm, Manavan <manava... at gmail.com> wrote:
> Hello everyone,
>    Since the real world objects often needs to be deleted even if they
> have some reference from some other object, I am going to use this
> approach to better model this situation, by cleaning up the attributes
> and assigning self.__class__ to a different class.
>  Any comment on this approach.
>
> class Deleted(object):
>     pass
>
> class RealWorldObj(object):
>     def __init__(self, *args):
>         self.attrs = args
>     def getAttrs(self,):
>         return self.attrs
>     def delete(self,):
>         del self.attrs
>         self.__class__ = Deleted
>
> >>> a = RealWorldObj(1,2,3)
> >>> print a.attrs
> (1, 2, 3)
> >>> a.delete()
> >>> a
>
> <__main__.Deleted object at 0x893ae2c>>>> a.attrs
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'Deleted' object has no attribute 'attrs'

Cute, but let me suggest that changing the class of the object would
make it harder to track down the original error.  So just delete the
attributes.  I'd also recommend using self.__dict__.clear() for that,
it gets all of them (usually) and doesn't need to be updated with you
add a new attribute to a class.


Carl Banks



More information about the Python-list mailing list