How to use dot notation for dict in python?

后端 未结 7 1485
醉话见心
醉话见心 2020-11-29 20:44

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:

相关标签:
7条回答
  • 2020-11-29 21:40

    __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

    0 讨论(0)
提交回复
热议问题