data = {
'class1': {
'a': {
'Chinese': 80},
'b': {
'Math': 90},
}
}
print(data)
print(data.class1)
print(data.class1.a)
print(data.class1.a.Chinese)
继承 dict
并实现 __getattr__(self, name)
class SuperDict(dict):
def __init__(self, *args, **kwargs):
super(SuperDict, self).__init__(*args, **kwargs)
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = SuperDict(value)
return value
# def __getitem__(self, item):
# '''[]运算符'''
# print('__getitem__', item)
# return self[item]
if __name__ == '__main__':
data = {
'class1': {
'a': {
'Chinese': 80},
'b': {
'Math': 90},
}
}
od = SuperDict(data)
print(od)
print(od.class1, od['class1'])
print(od.class1.a, od['class1']['a'])
print(od.class1.a.Chinese, od['class1']['a']['Chinese'])
# {'class1': {'a': {'Chinese': 80}, 'b': {'Math': 90}}}
# {'a': {'Chinese': 80}, 'b': {'Math': 90}} {'a': {'Chinese': 80}, 'b': {'Math': 90}}
# {'Chinese': 80} {'Chinese': 80}
# 80 80
或直接使用更强大的 EasyDict
安装
pip install easydict
代码
from easydict import EasyDict
data = {
'class1': {
'a': {
'Chinese': 80},
'b': {
'Math': 90},
}
}
data = EasyDict(data)
print(data['class1'].a.Chinese)
# 80