2015-02-11 152 views
3

我有一个班级(self.d1)中声明的字典。 调用F1功能后,self.d1必须更新到本地字典里面声明F1Python - 更新班级功能中的班级自我词典

import copy 

class num: 
    def __init__(self): 
     self.d1 = {'a':1, 'b':2, 'c':3} 
     self.f1(self.d1) 

     print self.d1 

    def f1(self,d): 
     d2 = {'d':4, 'e':5, 'f':6} 
     d = copy.deepcopy(d2) 

test = num() 

我期望的输出是:

{'d':4, 'e':5, 'f':6} 

但输出

{'a':1, 'b':2, 'c':3} 

我想了解问题所在,而不仅仅是解决方案

回答

3

你不想指定df1(),因为失去了旧的绑定它必须self.d1。所以在作业d之后只是局部变量f1()

但是你可以实现你想要有什么用:

class num: 
    def __init__(self): 
     self.d1 = {'a':1, 'b':2, 'c':3} 
     self.f1(self.d1) 

     print self.d1 

    def f1(self,d): 
     d2 = {'d':4, 'e':5, 'f':6} 
     d.clear() 
     d.update(d2) 

test = num() 

输出

{'e': 5, 'd': 4, 'f': 6} 

请注意,我的代码使得f1()没有分配到d,它不仅使调用,发生变异现有的对象。

有关此&相关主题的进一步参考,请参阅通过这样伟岸,斯内德尔德这个优秀的文章:Facts and myths about Python names and values

0

你是公关oblem是与

d = deepcopy(...) 

你不改变字典,d提到,你只需要改变d参考另一个字典(在这种情况下,一本字典的新创建的副本)。

+0

所以有反正改变原来的字典d被提到? – 2015-02-11 12:49:55

+0

是的 - 请参阅@PM-2Ring的答案 – 2015-02-11 12:54:25

0

如果值{'a' : 1}分配给一些变量self.d1那么该变量保持对价值的参考。这意味着您可以通过访问它来更改d1的值,例如:self.d1['a'] = 2,现在值将为{'a' : 2'}

您也可以通过将变量self.d1分配给新的东西来更改引用。因此,在您的功能f1中,您实际上更改d指向的引用,而不是其所指的值。由于功能范围的限制,self.d1仍然会保留对功能范围之外的原始值的引用。

0

Yust的其他解释...

class num: 

    def __init__(self): 

     self.d1 = {'a':1, 'b':2, 'c':3} 
     # calling a function with a dictionary copies the *reference* to the 
     # dictionary object. 

     print 'first test ..' 
     self.test_dict_arg_1(self.d1) 
     print self.d1 

     print 'second test ...' 
     self.test_dict_arg_2(self.d1) 
     print self.d1 

    def test_dict_arg_1(self, d): 

     d2 = {'d':4, 'e':5, 'f':6} 
     # now you load d with a new value, the referenced object is untouched 
     d = d2 

    def test_dict_arg_2(self, d): 

     d2 = {'d':4, 'e':5, 'f':6} 
     # now you work with the referenced object 
     d.clear() 
     d.update(d2)