[Python-au] New Python Class Features
Dave Cole
djc@object-craft.com.au
17 Jan 2003 15:51:27 +1100
> 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.
As far as I can remember, you just have to make sure that you do not
invoke __setattr__() in __init__() by doing this:
class foo:
def __init__(self):
self.__dict__['attrs'] = { 'knob1': 11, 'dial2': 'overdrive' }
- Dave
--
http://www.object-craft.com.au