python 字典转化成对象

>>> d = dict(a=1,b=4)
>>> d.a
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-e586b691db67> in <module>
----> 1 d.a

AttributeError: 'dict' object has no attribute 'a'

我们知道普通字典是不可以直接用.来访问字典的键值对,但是利用下面这个子类就可以啦

class Dict(dict):
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__

d = dict(a=1,b=4)
D = Dict(d)
原创文章 338 获赞 621 访问量 50万+

猜你喜欢

转载自blog.csdn.net/itnerd/article/details/105750390