【问题标题】:Accessing Plist items in a dict访问字典中的 Plist 项目
【发布时间】:2009-09-16 07:10:04
【问题描述】:

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

【问题讨论】:

    标签: python xml namespaces plist


    【解决方案1】:

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

    【讨论】:

    • 谢谢。事实证明,编写 plist 并将该文件加载到 dict 中更容易,无论如何我都必须这样做。
    【解决方案2】:

    您可以使用 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'
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2021-04-25
      相关资源
      最近更新 更多