首页 > 解决方案 > 在 python 中自定义 __delattr__

问题描述

以下是有效的__delattr__方法吗?

class Item:
    def __delattr__(self, attr):
        if attr in self.__dict__:
            print ('Deleting attribute: %s' % attr)
            super().__delattr__(attr)
        else:
            print ('Already deleted this attribute!')

具体来说,super()“实际删除”属性的正确方法是什么?并且是attr in self.__dict__检查属性是否在实例中的正确方法吗?

标签: pythonpython-3.x

解决方案


super 会调用父类对应的方法,你可以在这里实现自己的特殊方法,不需要参考它的 super 实现。考虑以下:

class Item:
    def __delattr__(self, attr):
        try:
            print ('Deleting attribute: %s' % attr)
            del self.__dict__[attr]
        except KeyError:
            print ('Already deleted this attribute!')

测试类:

>>> i.test = 'a value'
>>> del i.test
Deleting attribute: test
>>> del i.test
Deleting attribute: test
Already deleted this attribute!

推荐阅读