字典的python对象样式访问;无法弄清楚

时间:2018-03-01 13:20:30

标签: python getattr setattr

class ObjectDict(dict):
    """ allows object style access for dictionaries """

    def __getattr__(self, name):
        if name in self:
            return self[name]
        else:
            raise AttributeError('No such attribute: %s' % name)

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

    def __delattr__(self, name):
        if name in self:
            del self[name]
        else:
            raise AttributeError('No such attribute: %s' % name)

有人可以为我解释这段代码吗?我只是一个蟒蛇初学者。

2 个答案:

答案 0 :(得分:2)

ObjectDict实例是通过类继承的常规字典。见ObjectDict(dict)

__getattr__魔术函数允许定义任何对象的点符号访问。它只是在这里调用普通字典访问

同样,__setattr____delattr__允许使用点符号设置和删除(使用Python的del表达式)值。但是,要设置嵌套值,您需要第一个键的值也是ObjectDict

答案 1 :(得分:0)

__getattr__ 适用于获取数据的时间。

__setattr__ 适用于设置数据的时间。

__delattr__ 适用于 del 数据的时间。

现在,方法应该很清楚。

def __getattr__(self, name):
    # if the key exists... return it.
    if name in self:
        return self[name]
    # if not : raise an error.
    else:
        raise AttributeError('No such attribute: %s' % name)

def __setattr__(self, name, value):
    # set VALUE as value, with NAME as key in the dict.
    self[name] = value

def __delattr__(self, name):
    # if the key "name" exists in the dictionnary... delete it
    if name in self:
        del self[name]
    # else, it doesnt exist, so cant delete it.
    else:
        raise AttributeError('No such attribute: %s' % name)