How to use dot notation for dict in python?

后端 未结 7 1577
醉话见心
醉话见心 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:23

    You have to be careful when using __getattr__, because it's used for a lot of builtin Python functionality.

    Try something like this...

    class JuspayObject:
    
        def __init__(self,response):
            self.__dict__['_response'] = response
    
        def __getattr__(self, key):
            # First, try to return from _response
            try:
                return self.__dict__['_response'][key]
            except KeyError:
                pass
            # If that fails, return default behavior so we don't break Python
            try:
                return self.__dict__[key]
            except KeyError:
                raise AttributeError, key
    
    >>> j = JuspayObject({'foo': 'bar'})
    >>> j.foo
    'bar'
    >>> j
    <__main__.JuspayObject instance at 0x7fbdd55965f0>
    

提交回复
热议问题