相关疑难解决方法(0)

如何在python中使用dict的点符号?

我是python的新手,我希望我能用.符号来访问a的值dict.

让我们说我test喜欢这样:

>>> test = dict()
>>> test['name'] = 'value'
>>> print(test['name'])
value
Run Code Online (Sandbox Code Playgroud)

但是,我希望我能做到test.namevalue.事实上,我通过覆盖__getattr__我的类中的方法来做到这一点:

class JuspayObject:

    def __init__(self,response):
        self.__dict__['_response'] = response

    def __getattr__(self,key): 
        try:
            return self._response[key]
        except KeyError,err:
            sys.stderr.write('Sorry no key matches')
Run Code Online (Sandbox Code Playgroud)

这很有效!当我做:

test.name // I get value.
Run Code Online (Sandbox Code Playgroud)

但问题是当我test单独打印时,我得到的错误是:

'Sorry no key matches'
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

python dictionary nested

53
推荐指数
8
解决办法
6万
查看次数

标签 统计

dictionary ×1

nested ×1

python ×1