[Python-au] New Python Class Features

Daryl Tester Daryl.Tester@iocane.com.au
Fri, 17 Jan 2003 14:57:51 +1030

"Anthony Baxter" <anthony@interlink.com.au> wrote:

>> I'd recommend only using property for computed attributes (i.e. ones that
>> need a function call to calculate their value).  Most of the time you
>> need them.

> The other reason for using them is for preconditions (check something
> getting/setting) or postconditions (do something after getting/setting)

The way I've always found to do this (caveat: I haven't dabbled much beyond
1.5.2) is to use the access attribute methods of the object.  e.g. off the
top of my head:

class foo:
  def __init__(self):
    self.attrs = { 'knob1': 11, 'dial2': 'overdrive' }

  def __getattr__(self, name):
    if self.attrs.has_key(name):
      return self.attrs[name]
    raise "What you talkin' about, Willis?"  # Should be an IndexError, but
not as entertaining.

  def __setattr__(self, name, value):
    raise "I'm a read only object, dagnabbit"

And so on ... (from memory, there was a caveat lurking here about
cyclic lookups, but I'm not in front of the appropriate computer at
the moment).  You can then do funky pre/post conditions once
you've intercepted the object's get/set methods.