更新字典值的引用,而不是更新字典值

时间:2019-05-09 13:43:07

标签: python-3.x dictionary reference

我了解以下原因为何如此

v = 1
d = dict()
d['hi'] = v
d['hi'] = 2
print(v)  # prints 1 as expected

还有它为什么起作用:

class Node:
  def __init__(self,val):
    self.val = val


n = Node(1)
d['hi_node'] = n
d['hi_node'].val = 100
print(n.val)  # prints 100 as expected

我也相信我了解以下内容的工作原理:

n2 = Node(2)
d['hi_n2'] = n2
n3 = Node(3)
val_in_d = d['hi_n2']  # creates a new binding of name val_in_d
val_in_d = Node(3) # updates the location to which val_in_d points
print(n2.val) # still 2

但是是否有任何方法可以使用字典n2n3指向d,其作用与编写n2 = n3相似。因此,最后,如果我打印n2.val,我得到3,即我希望获取存储在字典中的值并更改其引用以指向另一个对象,而不仅仅是更新存储在字典中的值。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题是您没有更改指针的值,而是更改了指针本身。

n2 = Node(2)
d['hi_n2'] = n2
n3 = Node(3)
val_in_d = d['hi_n2']  # Here you get the pointer that points at n2
val_in_d = Node(3) # By assigning val_in_d to the Node constructor result you change the pointer
print(n2.val) # still 2

相反,您必须使用实际值,例如:

n2 = Node(2)
d['hi_n2'] = n2
n3 = Node(3)
val_in_d = d['hi_n2'] # Get pointer
val_in_d.val = 3 # Change value in the object,
print(n2.val) # Prints 3

或者,您可以创建一个中间人类/包装器,以防止python更改所需的指针,例如Python variable reference assignment