小编mat*_*LVW的帖子

如何访问名称中带有点的对象属性

我正在使用一堆类将字典转换为对象。

class Bunch(object):
    """ Transform a dict to an object """
    def __init__(self, kwargs):
        self.__dict__.update(kwargs)
Run Code Online (Sandbox Code Playgroud)

问题是,我有一个名称中带有点的密钥({'test.this':True})。

所以当我打电话时:

spam = Bunch({'test.this':True})
dir(spam)
Run Code Online (Sandbox Code Playgroud)

我有这样的属性:

['__class__',
 '__delattr__',
...
 '__weakref__',
 'test.this']
Run Code Online (Sandbox Code Playgroud)

但我无法访问它:

print(spam.test.this)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-ea63f60f74ca> in <module>()
----> 1 print(spam.test.this)

AttributeError: 'Bunch' object has no attribute 'test'
Run Code Online (Sandbox Code Playgroud)

我遇到了属性错误。

我怎样才能访问这个属性?

python

5
推荐指数
1
解决办法
3535
查看次数

标签 统计

python ×1