2017-10-08 68 views
0

我最近试图在Python中编写和操作一个类,并且遇到了一个奇怪的情况。每当我尝试操作一个类的实例化变量时,它只会影响它所在位置的变量。例如:在Python中,为什么类中某个变量的dictonary值发生变化,而不是变量本身?

class test: 
    def __init__(self): 
     self.test1 = 0 
     self.location = {"test1":self.test1} 
     self.row = [self.test1] 
def change(): 
    a = test() #instantiation 
    a.location['test1'] = 1 #Changing a.test1 to 1 within a dictionary 
    print(a.test1) #Print a.test 
    print(a.location['test1']) #Print a.test1 from within the dictionary where it was changed 
    print(a.row) #Print a list also containing a.test1 
change() 

输出到:

0 #Variable itself is unchanged 
1 #Variable in dictionary is changed 
[0] #Same variable referenced in list is unchanged as well 

为什么会出现这种情况,我怎么可能改变a.test1通过仅在字典改变它等于1?

+1

通过重新分配值,您不会重新分配实际属性。 –

+0

你似乎认为在你的类中对'self.test1'的引用以某种方式创建了对实例变量的永久引用。他们不是。这些引用相当于只使用'0'。有了这种理解,行为现在应该是明显的。 –

+0

“在Python中无法将变量链接到另一个变量” - 学习Python – 0TTT0

回答

1

发生这种情况是因为python整数是不可变的。所以,每次你用整数进行任何操作时,它实际上都会创建新的对象,而不是创建指向prevoius对象的指针。这可以easyly illustraded与下面的代码:

>>> a = 0 
>>> b = a 
>>> b += 1 
>>> a, b 
(0, 1) 

但是,如果你想使用列表,例如,你会得到这样的事情:

>>> a = [] 
>>> b = a 
>>> b.append(1) 
>>> a, b 
([1], [1]) 

在总结 - 你的代码的工作,因为它应该。另外,我建议你试试下面的代码片段:

class test: 
    def __init__(self): 
     self.test1 = [0] 
     self.location = {"test1": self.test1} 
     self.row = [self.test1] 


def change(): 
    a = test() #instantiation 
    a.location['test1'][0] = 1 #Changing a.test1 to 1 within a dictionary 
    print(a.test1) #Print a.test 
    print(a.location['test1']) #Print a.test1 from within the dictionary where it was changed 
    print(a.row) #Print a list also containing a.test1 

change() 

将产生你:

[1] 
[1] 
[[1]] 
0

改变什么self.location [“测试1”]等于不改变自身的价值.test1。

class Test: 
    def __init__(self): 
     self.test1 = 0 
     self.location = {"test1":self.test1} 
     self.row = [self.test1] 


def change(): 
    a = test() 
    a.location['test1'] = a.test1 = 1 
    a.row = [a.test1] 
    print(a.test1) 
    print(a.location['test1']) 
    print(a.row) 


change() 
0

当你指定的值要替换的self.test1参考字典。据我所知,没有办法“指向”字典值,或存储对它的引用。如果有人知道,请赐教。

相关问题