在字典中访问Plist项

0 投票
2 回答
756 浏览
提问于 2025-04-15 14:21

我有一个模块里的类,它可以读取一个plist(XML)文件,并返回一个字典。这非常方便,因为我可以这样说:

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的字典?

2 个回答

2

之所以不行,是因为在Python字典中,点操作符并不是正确的访问方式。你试图把它当成一个对象来访问它的属性,而实际上你应该是访问这个数据结构中的数据成员。

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'

撰写回答