python使用.操作符操作字典

覆盖Python内置字典的__getattr__和__setattr__方法,可以像操作js一样操作字典

直接上代码:

class Storage(dict):
    """
    A Stroage object is like a dictionary except `obj.foo` can be used inadition to `obj['foo']`
    """
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError as k:
            raise AttributeError(k)

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

    def __delattr__(self, key):
        try:
            del self[key]
        except KeyError as k:
            raise AttributeError(k)

    def __str__(self):
        return "<" + self.__class__.__name__ + dict.__repr__(self) + ">"

student = {"gjh":"shdfgj","sdfsd":"sdf"}
s = Storage(student)
print(s.gjh)
print(s.sdfsd)
print(s['gjh'])
print(s)

结果:
shdfgj
sdf
shdfgj

你可能感兴趣的:(python)