[Tutor] Class Attribute "Overloading?"
Vincent Gulinao
vincent.gulinao at gmail.com
Thu Aug 16 15:50:51 CEST 2007
I see, I think "property" is what I'm looking for.
But how would you design it yourself (you said it's a little ugly, I love to
hear better ideas)? My only concern is to avoid unnecessary DB accesses (or
any other expensive processes).
Thanks.
On 8/16/07, Tiger12506 <keridee at jayco.net> wrote:
>
>
> > Sorry about that. I want something like:
> >
> > class foo:
> >
> > def __init__(self):
> >
> > self.attr1 = None
> >
> >
> > def get_attr1(self):
> >
> > if not self.attr1:
> >
> > attr1 = <get value from DB, very expensive query>
> >
> > self.attr1 = attr1
> >
> > return self.attr1
> >
> >
> > such that:
> >
> > foo_instance = foo()
> >
> > then:
> >
> > foo_instance.get_attr1()
> >
> > and
> >
> > foo_instance.attr1
> >
> > gets the same value.
> >
> > Such that you get to derive attr1 only as needed and just once, both
> > outside
> > and within foo class.
> >
> > Or is it a bad idea or just plain ugly to do something like that? If it
> > is,
> > kindly suggest better approach.
> >
> > Thanks.
>
> It's a little ugly but not too bad. What you are describing are
> properties.
>
> class Foo:
> def _get_attr1(self):
> if not self.attr1:
> attr1 = TheValue
> return attr1
> def _set_attr1(self, value):
> self.attr1 = value
> ChangeDBFunction(value)
> attr1 = property(self._get_attr1,self._setattr1,None,None)
>
> I think that will work. The docs seem to suggest that you should subclass
> `object`.
> JS
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070816/7019d0a0/attachment.html
More information about the Tutor
mailing list