【发布时间】:2015-07-24 18:13:21
【问题描述】:
我有一个要销毁的对象的字典,如下所示。
class Elem:
def __init__(self, name):
self.name = name
.
.
def __del__(self):
print('destroying elem' + self.name)
class DerivedDict(dict):
def __init__(self):
super(DerivedDict, self).__init__()
def __del__():
for k in self.keys():
del self[k]
elem = Elem('myname')
ddict = DerivedDict()
ddict['myname'] = elem
# this line should delete the both the elem the entry in ddict.
del ddict
当我尝试这个时,我得到了这个错误
RuntimeError: dictionary changed size during iteration
【问题讨论】:
-
我收到此错误,这可能是与版本相关的差异,因为在 Python 3 中他们更改了
dict.keys() -
@Exellan:这正是我正在尝试的例子。我使用的python版本3.4.3
-
你真的需要在这些类中的任何一个中显式的析构函数吗?
del ddict使用默认析构函数将清理ddict及其元素,假设没有其他对这些元素的引用。 -
当这些项目被删除时,我会在日志中打印一些内容。有没有其他方法可以做到这一点,而不使用显式的析构函数?
标签: python python-3.x dictionary destructor