首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >列表中存储的zeep对象不断被覆盖

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

Stack Overflow用户
提问于 2019-06-21 07:27:41
回答 1查看 1.7K关注 0票数 1

我正在尝试将许多作为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
EN

回答 1

Stack Overflow用户

发布于 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)

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"})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56695043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档