我正在尝试将许多作为zeep
对象的变量附加到列表中。但是,当我在最后打印出列表时,列表中的每个变量都有相同的数据。
我尝试过在变量被覆盖时进行隔离,当我将一个新值放入具有相同名称的变量中时,就会发生这种情况,但我是在将变量追加到列表中之后执行此操作的。所以我很困惑为什么会发生这样的事情。我尝试使用不同的变量名,但它导致了相同的问题。
def create_json_list(json_template):
newVar = json_template
newVar['name'] = unique_name
list.append(newVar)
newVar = json_template
newVar['name'] = unique_name2
list.append(newVar)
print(list[0]['name'])
print(list[1]['name'])
# At this point, the same name gets printed twice
发布于 2019-06-21 07:42:05
您多次将同一对象追加到列表中。如果您注意到,模板正在被修改:
import json
template = {
"field1": 1,
"field2": "two"
}
json_list = list()
def create_json_list(json_template):
newVar = json_template
newVar['name'] = "unique_name"
json_list.append(newVar)
newVar = json_template
newVar['name'] = 'another_unique_name'
json_list.append(newVar)
print(json.dumps(json_template, indent=4))
create_json_list(template)
输出
{
"field2": "two",
"field1": 1,
"name": "another_unique_name"
}
您需要为每个条目创建一个新模板:
newVar = dict(json_template)
Assignment statements in Python do not copy objects, they create
bindings between a target and an object.
如果你想复制一个对象,你需要让Python知道。在dict
的情况下,您可以只使用上面所示的构造函数。
对于zeep
对象,您应该能够使用factory
factory = client.type_factory('ns0')
newVar = factory.JsonTemplate({"field1": 1, "field2": "two"})
https://stackoverflow.com/questions/56695043
复制相似问题