0

我在一个模块中有一个类,它读取一个 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']

突然它起作用了!

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

4

2 回答 2

2

It doesn't work because the dot operator is not proper accessor syntax for python dictionaries. You;re trying to treat it as an object and access a property, rather than accessing a data member of the data structure.

于 2009-09-16T08:51:00.123 回答
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'
于 2009-09-16T09:05:03.640 回答