How to customize getattr(obj, prop) function ?

Pierre meyer.p at gmail.com
Wed May 17 12:44:43 EDT 2006


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