[Zope-dev] Re: ComputedAttribute

Martijn Pieters mj@digicool.com
Wed, 10 Jan 2001 17:47:39 +0100


On Wed, Jan 10, 2001 at 04:13:49PM +0000, Chris Withers wrote:
> Martijn Pieters wrote:
> > 
> > Erm. The ExtensionClass.stx documentation hints at a ComputedAttribute
> > class (but as an example of how you could use an ExtensionClass). The
> > current C implementation of ComputedAttribute is not, as far as I can see,
> > documented.
> 
> Now I think I know the answer to this one, but I'll ask just to be sure:
> 
> class MyClass(Persistent Acquisition.Explicit):
> 
>      def _set_your_attribute (self,value):
> 	self._v_your_attribute = value
> 
>      def _get_your_attribute (self):
>          return self._v_your_attribute
> 
>      your_attribute = ComputedAttribute(_get_your_attribute)
> 
> ...with this class, your_attribute isn't going to play in Persistence,
> is it? (so I can update it lots without worrying about ZODB size
> growing... :-)

Yup, this allows you to alias your_attribute to _v_your_attribute without
creating an attribute that *will* persist in the process.

> Hmm... more questions:
> 
> If I do:
> 
> x = MyClass()
> x.your_attribute = 1
> 
> ...what happens?

your_attribute is set to one instead of the ComputedAttribute instance and
concequently persisted. If you want _set_your_attribute to be called, you
need to override __setattr__:

    def __setattr__(self, name, value):
        setter = getattr(self, '_set_' + name, None)
        if setter:
            setter(value)
	else:
	    raise AttributeError, "no such attribute: " + `name`

> Where do you import the ComputedAttribute module from?

from ComputedAttribute import ComputedAttribute

-- 
Martijn Pieters
| Software Engineer  mailto:mj@digicool.com
| Digital Creations  http://www.digicool.com/
| Creators of Zope   http://www.zope.org/
---------------------------------------------