getattr function

Ionel Simionescu ionel at psy.uva.nl
Fri Dec 17 11:08:10 EST 1999


Alwyn Schoeman <alwyns at prism.co.za> wrote in message
news:385A1D7D.19262C62 at prism.co.za...
| Hi,
|
| Could someone please explain this function to me? Specifically as
| it relates to use in classes and overloading?
|
| 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?
|
| def __getattr__(self, name):
|         return getattr(self.data,name)
|

Hi Alwyn,

X.attr_name is simply a reference for an arbitrary object <obj> that is
normally mapped by the __dict__ held by the object named X, under the name
"attr_name".

So, when obj is needed, the object named X is queried (by the interpreter).

First, the dictionary X.__dict__ is inspected.
1.
If this dict would map the string "attr_name" to any object, that object is
returned as the result of the query.
2.
If X.__dict__ does not have a key "attr_name", but X defines the method
__getattr__, then this method is passed the attribute name, and its returned
value is considered.


So, the general form of __getattr__ is:


def __getattr__(self, attr_name):
    if   attr_name == 'some_name':
        # ...
        return some_value
    elif attr_name == 'some_other_name':
        # ...
        return some_other_value
    elif ...

    else: raise NameError, attr_name


---
Note the last line.

Without it, your instance will return None for any attribute name for which
no proper object is defined. (Thanks to Friederich Lundh for pointing this
to me.)
---

In respect with your specific example, I am afraid that __getattr__ is only
as smart to return the right object as you design it.

__getattr__ does not know its context, it does not even assume anything the
object, <self> that you will pass it as first argument. Therefore,
__getattr__ cannot know to return a sort method for your specialized class
when you ask for an attribute called "sort".


ionel








More information about the Python-list mailing list