How to customize getattr(obj, prop) function ?

George Sakkis george.sakkis at gmail.com
Wed May 17 13:14:41 EDT 2006


Pierre wrote:

> Hi,
>
> Sorry in advance, english is not my main language :/
>
> I'd like to customize the result obtained by getattr on an object : if
> the object has the requested property then return it BUT if the object
> doesn't has actually this property return something else.
>
> In my case, I can't use getattr(object, property, default_value).
>
> I tried to write a class with a __getattr__ method and even a
> __getattribute__ method but this doesn't do what I want....
>
> Maybe I didn't correctly understand this :
> http://docs.python.org/ref/attribute-access.html
>
> Here is a piece of my code :
> =====================================
> class myclass:
>     """docstring"""
>
>     a = 'aa'
>     b = 'bb'
>
>     def __getattr___(self, ppt):
>         """getattr"""
>         if hasattr(self, ppt):
>             return self.ppt
>         else:
>             return "my custom computed result"

1) You have misspelled the method by adding a hard-to-spot third
trailing underscore.
2) __getattr__ is called when normal lookup fails, so the condition
evaluates always to False.

>     def __getattribute__(self, ppt):
>         """getattribute"""
>         if hasattr(self, ppt):
>             return self.ppt
>         else:
>             return "my custom computed result"

1) __getattribute__ is called for new-style classes only (those that
inherit directly or indirectly from object).
2) Even if your class was new-style, this would enter an infinite loop
because 'self.ppt' calls __getattribute__ again.

George




More information about the Python-list mailing list