我最近试图用Python编写和操作一个类,我遇到了一个奇怪的情况。每当我尝试操作类的实例化变量时,它只会影响变量所在位置的变量。例如:
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?
答案 0 :(得分:1)
这是因为python整数是不可变的。因此,每次使用整数进行任何操作时 - 它实际上都会创建新对象,而不是创建指向prevoius对象的指针。这可以通过以下代码轻松地说明:
>>> 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]]
答案 1 :(得分:0)
更改self.location [“test1”]等于的值不会更改self.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()
答案 2 :(得分:0)
当您将值分配给字典时,您将替换self.test1
引用。据我所知,没有办法“指向”字典值,或存储对它的引用。如果有人不知道,请赐教。