代码示例:
class AttrDict(dict):
def __getattr__(self, key):
print ('called " __getattr__" ')
return self[key]
def __setattr__(self, key, value):
print ('called "__setattr__" ')
if key in self.__dict__:
self.__dict__[key] = value
else:
self[key] = value
args = {'rec_nms_thresold': 0.5, 'batch_size': 1, 'image_shape': [3, 640, 640], 'threshold': 0.2}
args_dict = AttrDict(args)
print (args_dict.threshold)
args_dict.newAttr = '999'
print (args_dict.newAttr)
called " __ getattr __ "
0.2
called " __ setattr __ "
called " __ getattr __ "
999
参考链接:https://zhuanlan.zhihu.com/p/101004827?from_voters_page=true