How to automate accessor definition?
no.email at please.post
Mon Mar 22 14:54:27 CET 2010
In <mailman.1030.1269194878.23598.python-list at python.org> Dennis Lee Bieber <wlfraed at ix.netcom.com> writes:
>On Sun, 21 Mar 2010 16:57:40 +0000 (UTC), kj <no.email at please.post>
>declaimed the following in gmane.comp.python.general:
>> Regarding properties, is there a built-in way to memoize them? For
>> example, suppose that the value of a property is obtained by parsing
>> the contents of a file (specified in another instance attribute).
>> It would make no sense to do this parsing more than once. Is there
>> a standard idiom for memoizing the value once it is determined for
>> the first time?
> Pickle, Shelve? Maybe in conjunction with SQLite3...
I was thinking of something less persistent; in-memory, that is.
Maybe something in the spirit of:
# up for some "adaptive auto-redefinition"?
self.foo = self._some_time_consuming_operation()
...except that that assignment won't work! It bombs with "AttributeError:
can't set attribute".
PS: BTW, this is not the first time that attempting to set an
attribute (in a class written by me even) blows up on me. It's
situations like these that rattle my grasp of attributes, hence my
original question about boring, plodding, verbose Java-oid accessors.
For me these Python attributes are still waaay too mysterious and
unpredictable to rely on. Sometimes one can set them, sometimes
not, and I can't quite tell the two situations apart. It's all
very confusing to the Noob. (I'm sure this is all documented
*somewhere*, but this does not make using attributes any more
intuitive or straightforward. I'm also sure that *eventually*,
with enough Python experience under one's belt, this all becomes
second nature. My point is that Python attributes are not as
transparent and natural to the uninitiated as some of you folks
seem to think.)
More information about the Python-list