1

以下是我要在 python 中实现的要求:我有一个名为 context 的字典,它将从程序的各个部分更新。

现在我必须创建一个名为的 objenv来保存字典上下文和环境变量字典。

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对象也应该更新。

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

4

3 回答 3

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
于 2013-02-27T10:10:14.587 回答
0

Create a subclass of dict.

Objects have methods that get called if an attribute is missing. You can override the default implementation of these methods to do dictionary get and set operations.

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

Previous discussion here

If you need to create a new AttributeDict from an existing dictionary, you can use the following:

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

If you want a different object that just references an existing dictionary, use this

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

env = ReferencedDict(context)
print(env)
于 2013-02-27T06:37:12.233 回答
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'
于 2013-02-27T08:44:11.780 回答