__getattr__ feature
Greg Ewing
see at reply.address.invalid
Tue Jun 25 02:06:31 EDT 2002
Hans Nowak wrote:
> I didn't know this was possible:
>
> class Foo:
> def __init__(self, obj):
> self.obj = obj
> def __getattr__(self, name):
> return getattr(self.obj, name)
>
> foo = Foo([1,2,3])
> print foo[2] # prints 3
I think what's happening here is that invoking
the [] is causing a lookup for a __getitem__
method, and your __getattr__ is catching this
and redirecting it to self.obj, which does
have a __getitem__ method.
> A quick test learns that this is apparently a
> feature new to 2.2;
The new feature is that built-in types now
have all the relevant special methods accessible
by __xxx__ names. Previously they only worked
on user-defined classes.
> Does anybody
> know how/why this works and why it was added?
I don't think it was explicitly added -- it's
just a side effect of the type/class unification
stuff.
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list