[Zope-dev] Can't return / publish object of a dictionary?

Jeff Rush jrush@taupro.com
Fri, 17 Jan 2003 04:03:56 -0600


Lars Heber wrote:

> I've got two other questions:
> 
> 1. Say we have a Class A with an attribute myObjects which is just a
> list.
> Now, I'd like to write my own Class B(A) - it extends A.
> But, in Class B, myObjects has to be a method because it has to be
> rebuild everytime it is called.
> So, how can I do something like:
> myObjects = getMyObjects() ?
> I tried to do this in the class itself, didn't work.
> Also tried self.myObjects = self.getMyObjects() - result wasn't what I
> wanted, myObjects got (of course) the resulting list of getMyObjects(),
> but I need myObjects to be a reference to getMyObjects()

I use a form of the following to compute dynamic titles for Zope
objects, where the 'title' attribute is the result of a method call.
Modifying it slightly for your case...

from ComputedAttribute import ComputedAttribute

Class B(A):
     def getMyObjects(self):
         ...
     myObjects = ComputedAttribute(lambda self: self.getMyObjects())



> 2. Class A has another attribute, say data, which I want to control in
> Class B(A),
> i. e. everytime data is accessed (reading or writing), I want to
> intercept those actions.
> If it was just reading, I could use the strategy from 1., but I also
> want to control made changes to that attribute. Do I absolutely have to
> rewrite all the methods which access the wanted attribute, or is there
> another possibility with some kind of references, perhaps similar to
> software interrupts in DOS?

I'm not sure about this one, but I suspect an override of the 
__getattr__() method will let you intercept the lookup of the 'data' 
attribute, do any pre/post actions you wish, then return the real 
'data'.  You might try a ComputedAttribute arrangement instead and see 
if it works for your case since that would be easier.  __getattr__
overrides can get into infinite loops w/o careful designs.

Jeff Rush