Attribute monitoring in a class

Laurent Pointal laurent.pointal at limsi.fr
Wed Mar 14 07:03:58 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) )
> 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????
> Like for example
> 
> /class Class:
>    def __init__();
>       self.attr = "whatever"
> 
>    def __attrChangeFunction__():
>       print "It has changed"

Use a property. Extract from Python 2.3 docs:
"""
property(  	[fget[, fset[, fdel[, doc]]]])
    Return a property attribute for new-style classes (classes that
derive from object).

    fget is a function for getting an attribute value, likewise fset is
a function for setting, and fdel a function for del'ing, an attribute.
Typical use is to define a managed attribute x:

    class C(object):
        def getx(self): return self.__x
        def setx(self, value): self.__x = value
        def delx(self): del self.__x
        x = property(getx, setx, delx, "I'm the 'x' property.")

    New in version 2.2.
"""

> obj = Class()
> obj.attr = "other whatever"
> 
> *Output:*
> It has changed
> 
> /
> Thanks for the help.
> Regards/
> /

A+

Laurent.



More information about the Python-list mailing list