我正面临一个特殊的问题。我将在下面简要描述 假设我有这段代码-
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}$
如果
__postBodies
不是一个类属性,就像现在定义的那样,只是一个实例属性呢?在每次调用
MyClass.__parseFileAsText()
时都可能返回同一个字典,这可能有两种常见的方式:__parseFileAsText()
接受mutable default argument(您最终返回的dict)确保在每次调用
__parseFileAsText()
时都创建一个新字典,应该可以解决此问题。在编辑:根据您更新的问题中的
__parseFileAsText()
的代码,您的问题是您在每次调用时都重复使用相同的字典:在每次调用中,您都在修改
^{pr2}$StaticConfig.PASTE_PARAMS
,最终结果是列表中的所有正文字典实际上都是对StaticConfig.PASTE_PARAMS
的引用。根据StaticConfig.PASTE_PARAMS
是什么,您应该将该顶行更改为以下内容之一:如果} ,但最好自己用这些默认值填充{}。在
StaticConfig.PASTE_PARAMS
中的任何值是可变的,您可以使用^{相关问题 更多 >
编程相关推荐