以下是有效的__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__检查属性是否在实例中的正确方法吗?
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
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!
添加回答
举报
0/150
提交
取消