【问题标题】:python object style access for dictionaries ; cant figure it out字典的python对象样式访问;想不通
【发布时间】:2018-03-01 13:20:30
【问题描述】:
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)

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

【问题讨论】:

标签: python getattr setattr


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    __getattr__ 用于获取数据。

    __setattr__ 用于设置数据。

    __delattr__ 适用于您想要删除数据的时候。

    现在,方法应该很清楚了。

    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)
    

    【讨论】:

    • 非常感谢
    • 如果您发现它对您最有帮助,我邀请您接受答案。 :)
    猜你喜欢
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多