列表中存储的zeep对象不断被覆盖

时间:2019-06-20 23:27:40

标签: python-2.7 zeep

我试图将许多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

1 个答案:

答案 0 :(得分:0)

您多次将同一对象附加到列表。如果您注意到,模板正在被修改:

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)

来自documenation

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"})