[ZODB-Dev] Pickling methods and workarounds
Kapil Thangavelu
hazmat at objectrealms.net
Fri Feb 27 23:46:42 EST 2004
On Fri, 2004-02-27 at 18:30, Christian Robottom Reis wrote:
"""
My plan is to call foo() and it have the right method be called, based
on what the bar attribute is set to. However, this bombs out on me with
the too familiar
"""
try a ComputedAttribute, its another magically delicious extensionclass
;-)
from ComputedAttribute import ComputedAttribute
from Persistence import Persistent
class rabbit(Persistent):
def __init__(self):
self.eaten = 0
def carrots(self):
print 'yummy'
def chocolate(self):
print 'tasty'
def _getfood(self):
self.eaten +=1
if self.eaten%2:
return self.carrots
else:
return self.chocolate
eat = ComputedAttribute(_getfood)
velveteen = rabbit()
for i in range(10):
velveteen.eat()
check out the extensionclass docs for details.. it uses the __of__
extensionclass protocol for attribute access.
cheers,
-kapil
On Fri, 2004-02-27 at 18:30, Christian Robottom Reis wrote:
> On Fri, Feb 27, 2004 at 07:35:50PM -0300, Christian Robottom Reis wrote:
> > So today I ended up having to modify the behaviour in one of my
> > classes, and my initial plan was to customize this behaviour using a
> > method stored as an instance attribute. So I had something like:
>
> [...]
>
> > situations like these. The ones I see at the moment are:
> >
> > - Storing the method name as an instance attribute, and doing:
> >
> > def __init__(self):
> > self.plan_method = "_real_bar_A"
> >
> > def enable_plan_b(self):
> > self.plan_method = "_real_bar_B"
> >
> > # ...
> >
> > def foo(self):
> > getattr(self, self.plan_method)(0)
> >
> > which is quite ugly.
> >
> > - Using an if clause in foo(), which adds some minor overhead, but
> > uglifies the code in every callsite that wants to call bar().
>
> - Providing __setstate__ and __getstate__ methods that set the
> method and delete it based on an instance attribute used as a
> flag.
>
> Any other -- potentially nicer -- ways to do this?
>
> Take care,
> --
> Christian Robottom Reis | http://async.com.br/~kiko/ | [+55 16] 261 2331
>
> _______________________________________________
> For more information about ZODB, see the ZODB Wiki:
> http://www.zope.org/Wikis/ZODB/
>
> ZODB-Dev mailing list - ZODB-Dev at zope.org
> http://mail.zope.org/mailman/listinfo/zodb-dev
>
More information about the ZODB-Dev
mailing list