题目
请写一个类继承dict类,支持
.
方式访问
mydict = Mydict()
mydict.a = 1
mydict.b = 2
mydict.c.d = 3
print mydict
print mydict.c
输出:
{'a': 1, 'c': {'d': 3}, 'b': 2}
{'d': 3}
回答
class MyDict(dict):
def __getattr__(self, name):
return self.setdefault(name, MyDict())
def __setattr__(self, name, value):
self[name] = value
if __name__ == "__main__":
dct = MyDict()
dct.a = 1
dct.b = 2
dct.c.b = 3
print(dct)
print(dct.c)
网友评论