问题

python的的字典非常的好用,但是敲多了就会发现总是dict['key']这样的语法,多敲了不少字符,能不能使用.语法直接使用呢?

解决

其实在python中可以继承dict类,重写内部__getattr____setattr__方法就可以实现了

案例:

class Dict(dict):
    '''
    Simple dict but support access as x.y style.
    '''
    def __init__(self, names=(), values=(), **kw):
        super(Dict, self).__init__(**kw)
        for k, v in zip(names, values):
            self[k] = v

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

使用:

d = Dict()
d.name = 'hesan'
d.url = 'http://www.h3blog.com'

print(d)
print(d.name)
print(d.url)

print(d['name'])
print(d['url'])

输出

{'name':'hesan', 'url':'http://www.h3blog.com'}
hesan
http://www.h3blog.com

hesan
http://www.h3blog.com