- 论坛徽章:
- 1
|
看这个,支持递归的调用,例如:
foo = {
'a': 1,
'b': 2,
'c': {
'a': 22,
},
}
x = common.DictObj()
x.foo = foo
x['age'] = 100
print x.foo.c.a # output 22
print x.age #output 100- import types
- __all__ = ["DictObj"]
- class DictObj(types.DictType):
- def __init__(self):
- types.DictType.__init__(self)
-
- def __getitem__(self, key):
- return self.__dict__[key]
-
- def __repr__(self):
- return str(self.__dict__)
-
- def __setattr__(self, key, value):
- x = {}
- y = DictObj()
-
- if hasattr(value, "__dict__"):
- x = vars(value)
- elif isinstance(value, types.DictType):
- x = value
- else:
- x = value
- if isinstance(x, types.DictType):
- for k in x.keys():
- setattr(y, k, x[k])
- else:
- y = x
- print key, y
- self.__dict__[key] = y
-
- def __setitem__(self, key, value):
- if hasattr(value, "__dict__"):
- v = DictObj(value)
- else:
- v = value
-
- setattr(self, key, v)
复制代码 |
|