[Tutor] Keeping a list of attributes of a certain type

Kent Johnson kent37 at tds.net
Thu Jan 14 12:40:12 CET 2010


On Wed, Jan 13, 2010 at 9:24 PM, Guilherme P. de Freitas
<guilherme at gpfreitas.com> wrote:
> Hi everybody,
>
> Here is my problem. I have two classes, 'Body' and 'Member', and some
> attributes of 'Body' can be of type 'Member', but some may not. The
> precise attributes that 'Body' has depend from instance to instance,
> and they can be added or deleted. I need any instance of 'Body' to
> keep an up-to-date list of all its attributes that belong to the class
> 'Member'. How do I do this?

If you want to keep track of attributes as they are added and deleted,
you should override __setattr__() and __delattr__() in your Body
class.
http://docs.python.org/reference/datamodel.html#customizing-attribute-access
Here is a simple example:

In [4]: class LogAttributes(object):
   ...:     def __setattr__(self, name, value):
   ...:         print 'setting', name, 'to', value, type(value)
   ...:         object.__setattr__(self, name, value)
   ...:     def __delattr__(self, name):
   ...:         print 'removing', name
   ...:         object.__delattr__(self, name)

In [5]: l = LogAttributes()

In [6]: l.foo = 'bar'
setting foo to bar <type 'str'>

In [7]: l.foo
Out[7]: 'bar'

In [8]: del l.foo
removing foo

Kent


More information about the Tutor mailing list