gpt4 book ai didi

python - 什么时候修改赋值变量会影响原变量的值?

转载 作者:行者123 更新时间:2023-11-28 21:28:38 33 4
gpt4 key购买 nike

>>> x = 10
>>> y = x
>>> y = 100
>>> y # Changes on y will not be transferred to x
100
>>> x
10

>>> x2 = 'hello'
>>> y2 = x2
>>> y2 = 'world' # Changes on y2 will not be transferred to x2
>>> y2
'world'
>>> x2
'hello'

>>> a = [1, 2]
>>> b = a
>>> b.append(3) # Changes on b will be transferred to a
>>> b
[1, 2, 3]
>>> a
[1, 2, 3]

>>> x1 = {}
>>> y1 = x1
>>> y1['h'] = 'hhh' # Changes on y1 will be transferred to x1
>>> y1
{'h': 'hhh'}
>>> x1
{'h': 'hhh'}

问题> 在哪些情况下,赋值变量的值会影响值原始变量?

Python版本:‖Python 3.1.2

最佳答案

  • 在某些情况下,您随后会重新绑定(bind)其中一个名称,但不会重新绑定(bind)另一个名称,因此它们现在绑定(bind)到不同的对象。

    y = 100      # Rebind y. Doesn't change x.
    y2 = 'world' # Rebind y2. Doesn't change x2.
  • 在其他情况下,您正在改变对象。然后两个名字都看到对象的变化。

    b.append(3)      # Mutates the list that both a and b are bound to.
    y1['h'] = 'hhh' # Mutates the dictionary that both x1 and y1 are bound to.

关于python - 什么时候修改赋值变量会影响原变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7615730/

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