How to customize getattr(obj, prop) function ?

Richard Copeland rick446 at usa.net
Wed May 17 12:56:33 EDT 2006


Try this:

class Class:
     a='aa'
     b='bb'
     def __getattr__(self, ppt):
         return 'custom computed result'

__getattr__ is only called when "normal" attribute lookup fails, so 
there's no need for the "hasattr" test.

Also, I believe that __getattribute__ only applies to new-style classes 
(classes derived from "object"), and it will override *all* attribute 
accesses, anyway (meaning you'd have infinite recursion if you used it 
since you look up "self.ppt")

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"
> 
>     def __getattribute__(self, ppt):
>         """getattribute"""
>         if hasattr(self, ppt):
>             return self.ppt
>         else:
>             return "my custom computed result"
> 
> if __name__ == "__main__":
> 
>     d = myclass()
>     p1 = getattr(d, "a")
>     print p1
>     p2 = getattr(d, "b")
>     print p2
>     p3 = getattr(d, "c")
>     print p3
> ================================
> 
> I get an AttributeError when accessing to the property named "c".
> 
> Any explanation/solution to my problem ?
> 



More information about the Python-list mailing list