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 :
Here is a piece of my code :
=============== =============== =======
class myclass:
"""docstrin g"""
a = 'aa'
b = 'bb'
def __getattr___(se lf, 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 ?
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 :
Here is a piece of my code :
=============== =============== =======
class myclass:
"""docstrin g"""
a = 'aa'
b = 'bb'
def __getattr___(se lf, 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 ?
Comment