Attribute monitoring in a class

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Mar 14 07:03:12 EDT 2007


Joel Andres Granados a écrit :
> Hi list:
> 
> I have googled quite a bit on this matter and I can't seem to find what 
> I need (I think Im just looking where I'm not suppose to :).  I'm 
> working with code that is not of my authorship and there is a class 
> attribute that is changes by directly referencing it (object.attr = 
> value) instead of using a getter/setter (object.setAttr(Value) ) 

Which is the right thing to do in Python (I mean : *not* using 
Java-style getters/setters).

> function.  The thing is that I have no idea when the change occurs and I 
> would REALLY like to find out.
> So here comes my question .....
> Is there a function construct inside a python class that is 
> automatically called when an attr is changed????

yes : object.__setattr__(self, name, value)

# example:
class Class(object):
    def __init__();
       self.attr = "whatever"

    def __setattr__(self, name, value):
       object.__setattr__(self, name, value)
       if name == 'attr':
           print "It has changed"
           # you can also print the call frame,
           # or set a 'hard' breakpoint here...

obj = Class()
obj.attr = "other whatever"

*Output:*
It has changed


Or you might turn attr into a property:

class Class(object):
    def __init__();
       self.attr = "whatever"

    @apply
    def attr():
        def fset(self, value):
            self._attr = value
            print "It has changed"
        def fget(self):
            return self._attr
        return property(**locals())

But unless you have other needs than simple tracing/debugging, it's 
probably overkill.

HTH



More information about the Python-list mailing list