getattr function

Fredrik Lundh fredrik at pythonware.com
Fri Dec 17 06:57:08 EST 1999


Alwyn Schoeman <alwyns at prism.co.za> wrote:
> Could someone please explain this function to me? Specifically as
> it relates to use in classes and overloading?

__getattr__ is called as a last resort, when Python
fails to resolve an attribute name in any other way.

the docs say:

    "Called when an attribute lookup has not found
    the attribute in the usual places (i.e. it is not
    an instance attribute nor is it found in the class
    tree).

    Note that if the attribute is found through the
    normal mechanism, __getattr__() is not called."

see any available python introduction for more info
on how this works.

(the technical details can be found under "class instances"
here: http://www.python.org/doc/current/ref/types.html )

> Say I've got my own listthingy class without a sort, if I now do
> X.sort() I can see that a method in my class which looks like
> def __getattr__(self, name),  that sort is probably the name
> parameter.  But how does it know that it must do a list type sort
> or does this work just because sort is kindof generic?

afaik, it doesn't work -- unless you implement it your-
self.  and if you do, it's usually easier to just define a
"sort" method, and let python handle the rest in the
usual way...

</F>





More information about the Python-list mailing list