Python 如何访问名称中带有点的对象属性
我使用bunch类将dict转换为对象Python 如何访问名称中带有点的对象属性,python,Python,我使用bunch类将dict转换为对象 class Bunch(object): """ Transform a dict to an object """ def __init__(self, kwargs): self.__dict__.update(kwargs) 问题是,我有一个名称中有点的键({'test.this':True}) 所以当我打电话时: spam = Bunch({'test.this':True}) dir(spam) 我有一个阁楼:
class Bunch(object):
""" Transform a dict to an object """
def __init__(self, kwargs):
self.__dict__.update(kwargs)
问题是,我有一个名称中有点的键({'test.this':True})
所以当我打电话时:
spam = Bunch({'test.this':True})
dir(spam)
我有一个阁楼:
['__class__',
'__delattr__',
...
'__weakref__',
'test.this']
但我无法访问它:
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'
print(spam.test.this)
---------------------------------------------------------------------------
AttributeError回溯(最近一次呼叫上次)
在()
---->1个打印(垃圾邮件。测试。此)
AttributeError:“Bunch”对象没有属性“test”
我有一个属性错误
如何访问此属性?尝试spam[“test.this”]或spam.get(“test.this”)实现:
编辑:
我不建议直接从d
实例的客户端访问d.\uu dict\uuu
。客户端代码如下
d = D({"foo": 1, "bar.baz": 2})
print(d.__dict__.get("bar.baz"))
试图进入d
的内裤,需要了解d
的实施细节。您可以使用:
或者,您可以从对象的\uuu dict\uuu
获取值。用于获取垃圾邮件的目录:
>>> vars(spam)['test.this']
True
正确的建议是避免在变量中使用点。 即使我们以某种方式使用,也最好使用getattr获得它
getattr(spam, 'test.this')
如果我们在标准上很固执,那么这可能会有所帮助
class Objectify(object):
def __init__(self, obj):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
class Bunch(object):
""" Transform a dict to an object """
def __init__(self, obj, loop=False):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
spam1 = Bunch({'test': {'this': True}})
print(spam1.test.this)
spam2 = Bunch({'test': {'this': {'nested_this': True}}})
print(spam2.test.this.nested_this)
未提供测试。此作为键。您可能希望创建一个嵌套的dict,该dict循环遍历带有点的键。因为还没有提到:实际的解决方案是避免变量名中出现点,而是使用
snake\u case
。除非您没有重命名变量的选项。@Arne我认为不必避免点。类的行为类似于dict并允许包含点的名称,这是有效的用例。完全没有理由在这个答案中出现\uuuuu getitem\uuuuu
。相关部分为self.\u dict\u.get
。它不必位于\uuu getitem\uu
中。我建议把它去掉。这可能会让一些人感到困惑。d.d
实例的客户端不应该访问它。这是真的,但这并不意味着类必须实现\uu getitem\uu
。您可以实现一个get\u attribute
方法,或者随意调用它。您的回答使它看起来像是实现\uuuu getitem\uuuuu
是这项工作所必需的。这不是必需的,但推荐使用。如果存在\uu getitem\uuuuu
为什么要发明get\u属性呢?我喜欢这些答案,它们使用内置的。
getattr(spam, 'test.this')
class Objectify(object):
def __init__(self, obj):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
class Bunch(object):
""" Transform a dict to an object """
def __init__(self, obj, loop=False):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
spam1 = Bunch({'test': {'this': True}})
print(spam1.test.this)
spam2 = Bunch({'test': {'this': {'nested_this': True}}})
print(spam2.test.this.nested_this)