如何在python中为dict使用点表示法? [英] How to use dot notation for dict in python?

查看:41
本文介绍了如何在python中为dict使用点表示法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 非常陌生,我希望我可以使用 . 符号来访问 dict 的值.

假设我有这样的 test:

<预><代码>>>>测试 = dict()>>>测试['名称'] = '值'>>>打印(测试['名称'])价值

但我希望我可以做 test.name 来获得 value.事实上,我是通过像这样覆盖我的类中的 __getattr__ 方法来做到的:

类 JuspayObject:def __init__(self,response):self.__dict__['_response'] = 响应def __getattr__(self,key):尝试:返回 self._response[key]除了 KeyError,错误:sys.stderr.write('抱歉没有匹配的键')

这有效!当我这样做时:

test.name//我得到了值.

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

'抱歉没有匹配的键'

为什么会这样?

解决方案

这个功能已经存在于标准库中,所以我建议你只使用他们的类.

<预><代码>>>>从类型导入 SimpleNamespace>>>d = {'key1': 'value1', 'key2': 'value2'}>>>n = SimpleNamespace(**d)>>>打印(n)命名空间(key1='value1',key2='value2')>>>n.key2'值2'

添加、修改和删除值是通过常规属性访问实现的,即您可以使用像 n.key = valdel n.key 这样的语句.

再次回到字典:

<预><代码>>>>变量(n){'key1':'value1','key2':'value2'}

字典中的键应该是字符串 identifiers 用于属性访问正常工作.

在 Python 3.3 中添加了简单的命名空间.对于旧版本的语言,argparse.Namespace 有类似的行为.

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:

>>> test = dict()
>>> test['name'] = 'value'
>>> print(test['name'])
value

But I wish I could do test.name to get value. Infact I did it by overriding the __getattr__ method in my class like this:

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')

and this works! when I do:

test.name // I get value.

But the problem is when I just print test alone I get the error as:

'Sorry no key matches'

Why is this happening?

解决方案

This functionality already exists in the standard libraries, so I recommend you just use their class.

>>> from types import SimpleNamespace
>>> d = {'key1': 'value1', 'key2': 'value2'}
>>> n = SimpleNamespace(**d)
>>> print(n)
namespace(key1='value1', key2='value2')
>>> n.key2
'value2'

Adding, modifying and removing values is achieved with regular attribute access, i.e. you can use statements like n.key = val and del n.key.

To go back to a dict again:

>>> vars(n)
{'key1': 'value1', 'key2': 'value2'}

The keys in your dict should be string identifiers for attribute access to work properly.

Simple namespace was added in Python 3.3. For older versions of the language, argparse.Namespace has similar behaviour.

这篇关于如何在python中为dict使用点表示法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆