Roa*_*ord 3 python attributes del
我有一个字符串列表['foo1','foo2',...],表示我想从self中删除的变量,如果它们是self的一部分.什么是Pythonic和紧凑的方式来做到这一点?
我的第一次尝试是
if hasattr(self, 'foo1'):
del self.foo1
if hasattr(self, 'foo2'):
del self.foo2
...
Run Code Online (Sandbox Code Playgroud)
但是这显然不适用于大型列表.
有人可以帮忙吗?
Wil*_*sem 10
您可以使用for在同一时间循环,提升性能通过pop对__dict__对象的:
for attr in ('foo1','foo2'):
self.__dict__.pop(attr,None)
Run Code Online (Sandbox Code Playgroud)
pop基本上检查元素是否在字典中并删除它,如果是这种情况(它也返回相应的值,但这里不相关).我们None在这里也使用"默认"返回值,这样如果键不存在,pop则不会出错.
你可以用delattr.AttributeError如果属性不存在,它将引发一个属性,因此如果需要,可以将其包装在方法中:
def safe_delattr(self, attrname):
if hasattr(self, attrname):
delattr(self, attrname)
Run Code Online (Sandbox Code Playgroud)
或使用try/except块:
try:
delattr(self, attrname)
except AttributeError:
pass
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以使用定义的类__slots__,因为它们不公开__dict__属性.