python中的字典有key和value,我们需要使用dict[key]的方式获取value,书写比较麻烦。
可以改成类的对像通过”."的形式来访问字典元素。
class ObjDict(dict):
"""
Makes a dictionary behave like an object,with attribute-style access.
"""
def __getattr__(self,name):
try:
return self[name]
except:
raise AttributeError(name)
def __setattr__(self,name,value):
self[name]=value
如下图所示: