[Zope3-dev] keeping attributes abstract
Benji York
benji at zope.com
Thu Mar 9 04:29:12 EST 2006
Sam Stainsby wrote:
> So I'm inclines to use the IFooB approach by default to achieve more
> abstract attributes. Am I missing something here in the IFooA approach
> that allows me to do this anyway?
You are :) Python has properties. They give you a good migration path
from a simple attribute to what you would otherwise have to use
getter/setters for. An example would help. Today you do this:
class Foo(Persistent):
implements(IFooB)
bar = None
And then you decide, oops I need to calculate bar every time it's
accessed. Then you can do this:
class Foo(Persistent):
implements(IFooB)
@property
def bar(self):
return time.time() * 2 # crazy thing, but just an example
But that bar is read-only, what if you also want to be able to set bar,
you can do this:
class Foo(Persistent):
implements(IFooB)
@apply
def bar(self):
doc = """The bar attribute"""
def fset(self, bar):
if bar is None:
self._bar = 47
else:
self._bar = bar
def fget(self):
return self._bar * 44
return property(**locals)
Some people like a more explicit version of the last line, if so you can
use "return property(fset, fget, None, doc)".
(WARNING: I didn't actually run any of the code in this message, typos
may have crept in)
--
Benji York
Senior Software Engineer
Zope Corporation
More information about the Zope3-dev
mailing list