Detect when a class member is updated

Gerhard Häring gerhard.haering at opus-gmbh.net
Wed Jan 15 15:50:54 CET 2003


Steve Holden <sholden at holdenweb.com> wrote:
> "Boethius" <boethius at techie.com> wrote in message
> news:67446a0a.0301150634.f6d0c43 at posting.google.com...
>> Can I detect when a class member is added or updated?
>>
>> I have a class with a member called path. Everytime it's updated, I'd
>> like to run a 'sanity check' on the new value.
>>
>> How can I do this?
> 
> Take a look at "setattr()" generally, and the __setattr__() special method
> inparticular. This allows you to trap access to attributes.

That was necessary before properties were introduced in Python 2.2. So you
might as well write something like:

#v+
class MyClass(object):
    def __init__(self):
        self._path = None

    def _get_path(self):
        return self._path

    def _set_path(self, value):
        if isinstance(value, str): # a primitive check
            self._path = value
        else:
            raise ValueError

    path = property(_get_path, _set_path)
#v-

Note that properties only work with new-style classes (inherited from
object). See http://python.org/2.2.2/descrintro.html for details.

Gerhard
-- 
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/




More information about the Python-list mailing list