Python 在没有明显原因的情况下更改变量

时间:2021-07-05 13:52:07

标签: python dictionary variables

我有一个奇怪的 Python 行为,这可能是非常合理的,但我不明白。在此处查看此代码:

def changeDict(status):
    hotstatus = status
    for e in hotstatus:
        if hotstatus[e]:
            hotstatus[e] = "Successful"
        else:
            hotstatus[e] = "Failed"
    print(hotstatus)
    message = f"""
    Operation start: {hotstatus["operation-start"]}
    Operation stop: {hotstatus["operation-stop"]}
    """
    return message

def initalDict():
    status = {}
    status["operation-start"] = True
    status["operation-stop"] = False
    print(status)
    message = changeDict(status)
    print(message)
    print(f"This is the status: {status}")

initalDict()

这个输出是怎么来的:

{'operation-start': True, 'operation-stop': False}
{'operation-start': 'Successful', 'operation-stop': 'Failed'}

    Operation start: Successful
    Operation stop: Failed
    
This is the status: {'operation-start': 'Successful', 'operation-stop': 'Failed'}

最后一行不应该仍将 True 和 False 作为值读取吗? 我很迷茫。 如果有人能帮我解开这个谜,那就太好了:D。

亲切的问候

4 个答案:

答案 0 :(得分:0)

当您将字典 status 发送到函数 changeDict() 时,您将引用发送status 字典,而不是它的副本。 >

因此,更改 hotstatuschangeDict() 的值将更改 status 字典,因为两者都指向同一个对象。

您可以使用 hotstatus = status.copy() 来使用状态字典的副本。

This 会让您清楚了解这个概念背后的想法。

答案 1 :(得分:0)

在 Python 中 dict 是可变的,所以当你将一个赋值给另一个变量时:

 hotstatus = status  

只是为底层的、可变的 dict 创建一个别名。修改别名为 dicthotstatus,修改由变量名称 dict 引用的相同 status

如果你试试这个:

   import copy
   ... code ...
   hotstatus = copy.deepcopy(status)  

您将对 copy 所指的 dict 进行 status(实际上是深度复制,所有内容都将被复制,因此即使在该 {{1} } 它的所有内容也将被复制)所以 dict 有它自己的 hotstatus 可以使用。对 dict 的修改不会影响 hotstatus 所指的内容。

答案 2 :(得分:0)

我看到您正在使用 hotstatus = status。这使它们都指向相同的内存位置。所以当你更新一本字典时,它们都会被更新。

参考此链接了解更多信息: here

答案 3 :(得分:0)

当您执行 hotstatus = status 时,它不会创建字典输入的副本,您只是在更改名称,如果要创建副本,则应使用 hotstatus = status.copy(),然后您将能够在不改变状态的情况下编辑热状态