在列表中追加导致值溢出

2024-10-03 00:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正面临一个特殊的问题。我将在下面简要描述 假设我有这段代码-

class MyClass:

   __postBodies = []
    .
    .
    .
for the_file in os.listdir("/dir/path/to/file"):
      file_path = os.path.join(folder, the_file)
      params = self.__parseFileAsText(str(file_path)) #reads the file and gets some parsed data back
      dictData = {'file':str(file_path), 'body':params}
      self.__postBodies.append(dictData)
      print self.__postBodies
      dictData = None
      params = None

问题是,当我每次为不同的文件打印params和dictData时,它有不同的值(这是正确的),但是一旦发生了append,并且我打印了\uuu postBodies,就会发生一件奇怪的事情。如果有电子文件,假设A,B,C,那么

first time __postBodies has the content = [{'body':{A dict with some data related to file A}, 'file':'path/of/A'}]

second time it becomes = [{'body':{A dict with some data relaed to file B}, 'file':'path/of/A'}, {'body':{A dict with some data relaed to file B}, 'file':'path/of/B'}]

AND third time = [{'body':{A dict with some data relaed to file C}, 'file':'path/of/A'}, {'body':{A dict with some data relaed to file C}, 'file':'path/of/B'}, {'body':{A dict with some data relaed to file C}, 'file':'path/of/C'}]

所以,你可以看到'file'键工作得很好。奇怪的是,“body”键被覆盖了所有最后一个附加的条目。在

我犯了什么错误吗?有什么我必须做的吗?请给我指个方向。在

对不起,如果我不太清楚。在

编辑--------------------

self.\uuParseFileAsText(str(file_path))调用是一个dict,我将它作为“body”插入dictData中。在

第二版-----------------------------------

正如您所问的,这是代码,但是我检查了params=self.\uuParseFileAsText(str(file_path))调用每次都返回diff dict。在

^{pr2}$

Tags: ofthetopathselfdatawithbody
2条回答

如果__postBodies不是一个类属性,就像现在定义的那样,只是一个实例属性呢?在

每次调用MyClass.__parseFileAsText()时都可能返回同一个字典,这可能有两种常见的方式:

  • __parseFileAsText()接受mutable default argument(您最终返回的dict)
  • 修改类或实例的属性并返回该属性,而不是每次都创建一个新属性

确保在每次调用__parseFileAsText()时都创建一个新字典,应该可以解决此问题。在

编辑:根据您更新的问题中的__parseFileAsText()的代码,您的问题是您在每次调用时都重复使用相同的字典:

tempParam = StaticConfig.PASTE_PARAMS
...
return tempParam

在每次调用中,您都在修改StaticConfig.PASTE_PARAMS,最终结果是列表中的所有正文字典实际上都是对StaticConfig.PASTE_PARAMS的引用。根据StaticConfig.PASTE_PARAMS是什么,您应该将该顶行更改为以下内容之一:

^{pr2}$

如果StaticConfig.PASTE_PARAMS中的任何值是可变的,您可以使用^{},但最好自己用这些默认值填充{}。在

相关问题 更多 >