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

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

问题描述

我对python还是很陌生,希望我可以做.表示法来访问dict的值.

I'm very new to python and I wish I could do . notation to access values of a dict.

假设我有这样的test:

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

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

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.

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

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

'Sorry no key matches'

为什么会这样?

推荐答案

此功能已经

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'

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

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.

再次返回字典:

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

字典中的键应为字符串标识符,以进行属性访问正常工作.

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

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

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

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

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