如何访问字典项作为属性,反之亦然

时间:2013-02-27 06:20:27

标签: python

以下是我在python中实现的要求: 我有一个叫做上下文的字典,它将从程序的各个部分进行更新。

现在我必须创建一个名为env的obj,它还包含字典上下文和环境变量字典。

env对象应该具有字典类的所有功能,应该可以访问字典项作为对象的属性。

例如,

  

context = {'install_path' : '/home/xyz','cwd' : '/home/xyz/Desktop'}

  

context   字典将从程序的各个部分更新。

现在我必须创建保存上下文字典和环境字典的env对象。并且应该可以访问字典项作为env对象的属性。

例如:

print(env.install_path) # accessing item of context dictionary
print(env.os) #accessing environmental variable print(env)
print(env['install_path'])
print(env)

应该产生输出:

 /home/xyz linux 
 /home/xyz
 {'install_path':'/home/xyz','cwd':'/home/xyz/Desktop'}
 all envrionmental variables

稍后当更新上下文字典时,还应更新env对象。

请帮助如何实现这一目标。

3 个答案:

答案 0 :(得分:2)

这是做我见过的最简单的方法:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

if __name__ == '__main__':
    o = AttrDict(x=10)
    o.y = 20
    o['z'] = 30
    print o.x, o['y'], o.z

输出:

10 20 30

答案 1 :(得分:0)

创建dict的子类。

对象具有在缺少属性时调用的方法。您可以覆盖这些方法的默认实现来进行字典获取和设置操作。

class AttributeDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value

之前的讨论here

如果需要从现有字典创建新的AttributeDict,可以使用以下命令:

context = {'install_path' : '/home/xyz','cwd' : '/home/xyz/Desktop'}
new_dict = AttributeDict(context)
print new_dict.install_path

如果您想要一个仅引用现有字典的其他对象,请使用此

class ReferencedDict(object):
    def __init__(self, reference):
        self.ref = reference
    def __getattr__(self, value):
        return self.ref[value]

env = ReferencedDict(context)
print(env)

答案 2 :(得分:0)

这样的事情可以解决问题:

class DictWithReference(dict):

    def __init__(self, *args, **kwargs):
        self._ref_other = kwargs.pop("ref", {})
        super(DictWithReference, self).__init__(*args, **kwargs)

    def __getattr__(self, attr):
        return self.__getitem__(attr)

    def __getitem__(self, key):
        try:
            return super(DictWithReference, self).__getitem__(attr)
        except KeyError:
            return self._ref_other[attr]

用法:

>>> context = {'install_path' : '/home/xyz','cwd' : '/home/xyz/Desktop'}
>>> env = DictWithReference({'foo': 'bar'}, ref=context)
>>> env.foo
'bar'
>>> env['foo']
'bar'
>>> env.install_path
'/home/xyz'
>>> env['install_path']
'/home/xyz'