題目
請寫一個類繼承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)