CHH3213 / Note-Ubuntu_CHH3213

ubuntu系统CHH3213上做的笔记
0 stars 0 forks source link

78. python使用点操作符访问字典(dict)数据 #78

Open CHH3213 opened 2 years ago

CHH3213 commented 2 years ago

平时访问字典使用类似于:dict['name']的方式,如果能通过dict.name的方式访问会更方便,下面的代码自定义了一个类提供了这种方法。

#from http://www.sharejs.com
class DottableDict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self
    def allowDotting(self, state=True):
        if state:
            self.__dict__ = self
        else:
            self.__dict__ = dict()

d = DottableDict()
d.allowDotting()
d.foo = 'bar'

print(d['foo'])
# bar
print(d.foo)
# bar

d.allowDotting(state=False)
print(d['foo'])
# bar from http://www.sharejs.com
print(d.foo)
# AttributeError: 'DottableDict' object has no attribute 'foo'         
#该代码片段来自于: http://www.sharejs.com/codes/python/8716