Re: delattr missing?

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Tue, 16 Aug 1994 12:25:33 -0400

> >>> but no function to do "del instance.member" by name. Am I the only
> >>> one to have stumbled onto this (minor) problem? Is there a way to
> >>> do it?
> >
> >Guido> I guess it's just an oversight... And nobody missed it before.
> >Guido> Would it be acceptable if instead of adding a new function, I
> >Guido> add the "feature" that setattr(instance, 'member') is
> >Guido> equivalent to del instance.member?
> >

On Aug 16, 14:06, Guido Sohne wrote:
>
> Ummm. It works but isnt it nicer to have del instance.member ? I think it
> would be more logical and orthogonal. Internally it could be as you said.
>

'del instance.member' DOES exist and work currently.
setattr( instance, 'member' ) has the same effect except that 'member'
can be anything that evaluates to a string. Typically 'setattr' is
more useful for initializing attributes ( or in this proposed case,
destroying attributes ) when you have a list of elements. Without
setattr/getattr, you would have to do an eval of the string.

An example is a method I have posted before to create a wrapper
class for a built-in object type:

class MyFile:
def __init__( self, file )
self.__dict__.['__methods__'] = []
for meth in file.__methods__ :
# make 'file's methods my methods
setattr( self, meth, getattr( file, meth ))
self.__methods__.append( getattr(self, meth ))
# and then override or add to those methods...

Similarly, you might need a class with a "reset" methods, that deletes
all attributes not on a 'keep' list.

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics