python - 在 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__
检查属性是否在实例中的正确方法吗?
解决方案
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!
推荐阅读
- selenium - Can we pass priority and enabled from xls sheet for TestNg test?
- python - 在 Pandas 中通过窗口子句实现 MSSQL 的分区
- excel - 如何正确设置POST参数以接收指定日期的持股信息?
- python - Using yield, print and return in python function
- c# - 检查字符串的哪一部分没有被分割
- python-3.x - 使用 BeautifulSoup 代码审查进行网页抓取
- reactjs - react-redux 中的 CRUD,显示来自另一个页面的帖子详细信息
- ios - dispatch_sync 永远不会从块中返回
- python - Python,XML发送带有格式的POST请求
- jquery - Rails 中的 Masonry Jquery - 不刷新页面就无法工作