写torndb代码时发现d = db.query("select author from book limit 1;") 返回的对象既可以d[0].author又可以d[0]["author"]来访问.下面是给出方法
自己构造的字典
class ObjectDict(dict):
"""Makes a dictionary behave like an object, with attribute-style access.
"""
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
d = ObjectDict()
d.a = 4
d["b"] = 6
print d.a, d["a"]
print d.b, d["b"]
已存在的字典
d = {"a":4, "b":6}
obj_d = type("klass", (object, ), d)
print obj_d.a, obj_d.b