几个月来,我广泛阅读了Python中的不可变和可变对象,我似乎开始理解这个概念。我仍然无法发现为什么下面的代码会产生内存泄漏的问题。dict的功能是引用特定类型的不可变记录。在许多情况下,我得到一个现有记录的更新,在这种情况下,只有当两个记录(oldrecord
和newrecord
)不相等时,现有记录才会被更新。然而,我有一种感觉,如果oldrecord
和newrecord
匹配,newrecord
就永远不会被删除,尽管在这种情况下,所有引用似乎都不存在了。你知道吗
我的问题是:
下面的代码是基于记录类型选择dict引用的良好实践,还是我应该做不同的选择(例如通过dictSwitcher
)?你知道吗
class myRecordDicts():
def __init__(self, type1Dict=dict(), type2Dict=dict(),
type3Dict=dict(),type4Dict=dict(),type5Dict=dict(),type6Dict=dict(), type7Dict=dict()):
self.type1Dict = type1Dict
self.type2Dict = type2Dict
self.type3Dict = type3Dict
self.type4Dict = type4Dict
self.type5Dict = type5Dict
self.type6Dict = type6Dict
self.type7Dict = type7Dict
def dictSelector(self, record):
dictSwitcher = {
myCustomRecordType1().name: self.type1Dict,
myCustomRecordType2().name: self.type2Dict,
myCustomRecordType3().name: self.type3Dict,
myCustomRecordType4().name: self.type4Dict,
myCustomRecordType5().name: self.type5Dict,
myCustomRecordType6().name: self.type6Dict,
myCustomRecordType7().name: self.type7Dict,
}
return dictSwitcher.get(record.name)
def AddRecordToDict(self, newrecord):
dict = self.dictSelector(newrecord)
recordID = newrecord.id
if recordID in dict:
oldrecord = dict[recordID]
self.MergeExistingRecords(oldrecord,newrecord)
else:
dict[recordID] = newrecord
def MergeExistingRecords(self, oldrecord, newrecord):
# Basic Compare function
oldRecordString = oldrecord.SerializeToString()
newRecordString = newrecord.SerializeToString()
# no need to do anything if same length
if not len(oldRecordString) == len(newRecordString):
oldrecord.CustomMergeFrom(newrecord)
嗯,似乎总是这样:我在这个问题上工作了好几个小时,却没有取得进展。在StackExchange上正确表述问题5分钟后,我发现我的问题:
我需要删除init中的引用,因为我在实例化
myRecordsDicts()
时从未传递dict,以下代码不会泄漏内存:相关问题 更多 >
编程相关推荐