我最近试图在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?
通过重新分配值,您不会重新分配实际属性。 –
你似乎认为在你的类中对'self.test1'的引用以某种方式创建了对实例变量的永久引用。他们不是。这些引用相当于只使用'0'。有了这种理解,行为现在应该是明显的。 –
“在Python中无法将变量链接到另一个变量” - 学习Python – 0TTT0