How to create cross between __getattr__() and __getitem__()?
Darrell
news at dorb.com
Fri Dec 3 23:26:49 EST 1999
Assuming I understand, this might help.
attrs={'dog':1, 'cat':2}
class A:
def __getattr__(self, name):
print 'GET IT!'
global attrs
val=attrs.get(name,None)
if val:
setattr(self, name,val)
return val
a=A()
print a.dog
print a.dog
################ OUTPUT
GET IT!
1
1
--
--Darrell
"John Lull" <lull at acm.org> wrote in message
news:r8sg4sko7tjsstc9g544q697ji0s8ush0i at 4ax.com...
> 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
>
> --
> http://www.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list