forcing a definition to be called on attribute change

Bruno Desthuilliers onurb at xiludom.gro
Tue Oct 24 12:36:00 CEST 2006

Michael Malinowski wrote:
> Hey All, 
> Apologies if this is a stupidly obvious or simple question. If I have a
> class with a series of attributes, is there a way to run a function
> definition in the class

s/run a function definition in the class/call a method/

> whenever a specific attribute is changed?

Yes : properties.

> Something like the following 
> class cSphere() :

OT : prefixing classes names with 'c' is totally unpythonic.
> 	def __init__(self):
> 		Self.myAttr = 0


> 	def runThisFunctionWhenMyAttrChanged() :
> 		Pass

class MyClass(object):
  def __init__(self):
    self.my_attr = 0 # will call the setter
    # use direct attribute access instead if you don't
    # want to call the setter, ie:
    # self._my_attr = 0

  def _get_my_attr(self):
    return self._my_attr

  def _set_my_attr(self, val):
    self._my_attr = val

  my_attr = property(_get_my_attr, _set_my_attr)


bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list