How to create cross between __getattr__() and __getitem__()?
John Lull
lull at acm.org
Fri Dec 3 20:57:24 EST 1999
I'm trying to create a class where someting like:
x = instance.undefined[i]
works, given that "undefined" is the name of a previously-unknown
attribute.
I'd like to have that statement turn into one call something like:
instance.getAttrItem(self, "undefined", i)
which is invoked only once, with both the name of the unknown
attribute and the desired index.
Unfortunately, executing getAttrItem() is an expensive (ie very slow)
operation, so I can't afford to try it any more times than absolutely
necessary.
My first thought was to have __getattr__() return a new object,
containing a reference to "instance", the name of the attribute
requested, and a __getitem__() procedure to handle the indexing
operation by invoking newObject.instance.getAttrItem().
Unfortunately, though, I also need:
x = instance.undefined
to work normally (ie have __getattr__() invoke getAttrItem() without
specifying an index), but I can't see any way for __getattr__() to
know whether it should try getAttrItem() immediately or should create
and return the new object.
Can anyone suggest a (preferrably simple) way to accomplish this?
Thanks.
Regards,
John
More information about the Python-list
mailing list