gpt4 book ai didi

python - 按值字符串;引用字典?

转载 作者:行者123 更新时间:2023-11-28 20:36:44 24 4
gpt4 key购买 nike

我来自 C,正在学习 Python。在 Python (3.5.2) 中,似乎将一种数据类型赋值给另一种相同类型的数据有时是通过值完成的,有时是通过引用完成的。

例如,字符串按值赋值:

>>> str1 = "hello"
>>> str2 = str1
>>> print(str1, str2)
hello hello
>>> str2 = "goodbye"
>>> print(str1, str2)
hello goodbye

这是我期望的行为。但是,它与字典的工作方式不同:

>>> dict1 = {'key1':'val1', 'key2':'val2'}
>>> dict2 = dict1
>>> print(dict1, dict2)
{'key2': 'val2', 'key1': 'val1'} {'key2': 'val2', 'key1': 'val1'}
>>> dict2['key1'] = 'newval'
>>> print(dict1, dict2)
{'key2': 'val2', 'key1': 'newval'} {'key2': 'val2', 'key1': 'newval'}

请注意 dict1 dict2 都已更改。同样,如果我将键/值对添加到其中一个词典中,它将同时出现在两个词典中。 啊!

(抱歉,那是我的 C 背景):)

我如何知道任何给定变量类型的预期行为?有解决这种疯狂的方法吗?还是我只需要记住任意规则?

附言我意识到我可以通过使用 dict2 = dict(dict1) 获得预期的行为。


“可能的重复项”包含有关如何执行此操作的良好信息,但我对为什么我必须这样做很感兴趣。这个问题的答案已经很有帮助了!

最佳答案

在 Python 中,一切都是引用;这一点和C不同,变量不是盒子。赋值实际上是一个绑定(bind)。

str1 = "hello"
str2 = str1

str1str2 都引用了“hello”, 但是Python 中的string 是不可变的,所以 修改str2,会创建一个新的绑定(bind),因此不会影响 str1

的值
str2 = "hack"
# here str1 will still reference to "hello" object

字典的作用是一样的:

d1 = {"name": "Tom"}
d2 = d1

d2d1 将引用同一个对象。如果将 d2 更改为新值,则不会影响 d1 的值;但是相反,如果我们只修改 d2,比如 d2['age'] = 20d1 的值将会改变,因为他们共享同一个对象。

d2 = {"name": "Hack"}
# the value of d1 does not change

Luciano Ramalho 在 Fluent Python 第 8 章 Variables Are Not Boxes 部分对此进行了总结

To understand an assignment in Python, always read the righthand side first: that’s where the object is created or retrieved. After that, the variable on the left is bound to the object, like a label stuck to it. Just forget about the boxes.

关于python - 按值字符串;引用字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com