递归dict

一个看起来非常酷的定义

class Example(dict):
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
 
a = Example()
 
a[1][2][3] = 4
##a[1][3][3] = 5
##a[1][2]['test'] = 6

print(a)

结果:{1: {2: {3: 4}}}

posted @ 2014-04-20 20:59  LisPythoniC  阅读(159)  评论(0编辑  收藏  举报