我在模块I中有一个类,它读取plist(XML)文件并返回一个dict。这非常方便,因为我可以这样说:
Data.ServerNow.Property().DefaultChart
返回属性字典,特别是DefaultChart
的值。十分优雅。
但是,以这种方式组装字典会失败:
dict={'Data': 'text1', 'Name':'text2', 'Place':'text3]}
dict
看起来与Plist dict完全一样。
但是当我说
print TextNow.Data().Name
我收到错误
'dict' object has no attribute 'Name'
但如果我说
print TextNow.Data()['Name']
突然它起作用了!
有人可以解释这种行为吗?有没有办法将字典转换为XML-ish字典?
答案 0 :(得分:2)
它不起作用,因为点运算符不是python词典的正确访问器语法。您;尝试将其视为对象并访问属性,而不是访问数据结构的数据成员。
答案 1 :(得分:1)
您可以使用getattr重定义将字典键视为属性,例如:
class xmldict(dict):
def __getattr__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError:
if attr in self:
return self[attr]
else:
raise
所以,例如,如果你有以下dict:
dict_ = {'a':'some text'}
你可以这样做:
>> print xmldict(dict_).a
some text
>> print xmldict(dict_).NonExistent
Traceback (most recent call last):
...
AttributeError: 'xmldict' object has no attribute 'NonExistent'