I\'m very new to python and I wish I could do .
notation to access values of a dict
.
Lets say I have test
like this:
__getattr__
is used as a fallback when all other attribute lookup rules have failed. When you try to "print" your object, Python look for a __repr__
method, and since you don't implement it in your class it ends up calling __getattr__
(yes, in Python methods are attributes too). You shouldn't assume which key getattr will be called with, and, most important, __getattr__
must raise an AttributeError if it cannot resolve key
.
As a side note: don't use self.__dict__
for ordinary attribute access, just use the plain attribute notation:
class JuspayObject:
def __init__(self,response):
# don't use self.__dict__ here
self._response = response
def __getattr__(self,key):
try:
return self._response[key]
except KeyError,err:
raise AttributeError(key)
Now if your class has no other responsability (and your Python version is >= 2.6 and you don't need to support older versions), you may just use a namedtuple : http://docs.python.org/2/library/collections.html#collections.namedtuple