2009-09-16 43 views
0

我在模块I中有一个类,它读取plist(XML)文件并返回字典。这是非常方便的,因为我可以这样说:在字典中访问Plist项目

Data.ServerNow.Property().DefaultChart 

这将返回一个属性字典,专门为DefaultChart值。十分优雅。 然而,组装字典这种方式失败:

dict={'Data': 'text1', 'Name':'text2', 'Place':'text3]} 

dict长相酷似的plist字典。 但是,当我说

print TextNow.Data().Name 

我得到错误

'dict' object has no attribute 'Name' 

但如果我说

print TextNow.Data()['Name'] 

突然它的工作原理!

有人可以解释这种行为吗?有没有办法将字典转换为XML-ISH字典?

回答

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_ = {'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' 
2

它不起作用,因为点运算符不适合python字典的访问器语法。您;重新尝试将其视为对象并访问属性,而不是访问数据结构的数据成员。

+0

谢谢。事实证明,编写plist并将该文件加载到字典中是比较容易的,无论如何我必须这样做。 – Gnarlodious 2009-09-20 13:29:06