我有一个下面的类,它只是为我创建一个对象字典。然后将创建的字典main_dict
复制到一个新字典second_dic
。
import numpy as np
class MainClass:
def __init__(self):
self.main_dict = dict()
def add(self, k, val):
self.main_dict[k]=val
main_obj = MainClass()
for i in range(1,5):
main_obj.add(k=i, val=np.random.randint(1,10))
print(main_obj.main_dict)
{1: 1, 2: 2, 3: 7, 4: 7}
second_dic = main_obj.main_dict.copy()
print(second_dic)
{1: 1, 2: 2, 3: 7, 4: 7}
Python似乎不支持像C++这样的指针。因此,当我更改second_dic
中的值时,这些更改不会反映在main_dict
中。我想知道我有什么选择才能做到这一点。
second_dic[1]=1000
print(second_dic)
{1: 1000, 2: 2, 3: 7, 4: 7}
print(main_obj.main_dict)
{1: 1, 2: 2, 3: 7, 4: 7}
在上面的代码中,您对second_dic
所做的更改不会反映在main_dict
中,因为它们为什么会反映出来?这两者是两个完全不同的字典对象。
如果想要别名(尽管这确实不建议,因为它会导致难以检测的错误(,你必须分配引用(有点像C++指针(:
second_dic = main_obj.main_dict # Now second_dic is a pointer to main_dict, in a way
second_dic[1] = 1000
print(main_obj.main_dict)
{1: 1000, ...}
second_dic
和main_dict
的地址不同。因此,对second_dic
所做的更改将不会反映到main_dict
。我使用了上面相同的代码,并显示了他们的地址,不出所料,他们是不同的。
>>> id(second_dic) # To print the address
1911354287192
>>> id(main_obj.main_dict) # To print the address
1911354286952
如果您需要second_dic
指向main_dict
。我们可以按以下方式来做。
>>> main_obj.main_dict
{1: 6, 2: 10, 3: 10, 4: 3}
>>> second_dic = main_obj.main_dict # pointing to the same location
>>> second_dic
{1: 6, 2: 10, 3: 10, 4: 3}
>>> second_dic[1] = 111 #Changes the value
>>> second_dic
{1: 111, 2: 10, 3: 10, 4: 3}
>>> main_obj.main_dict # Value gets reflected.
{1: 111, 2: 10, 3: 10, 4: 3}