所以从第二个对象调用的方法ChangeDictionary也在第一个对象中改变了值。
我创建了一个类,其中包含一个字典变量和一个用于编辑它的方法:
class Test:
TestDict = {"TestKey": "OldValue"}
def ChangeDictionary(self):
self.TestDict["TestKey"] = "NewValue"
然后创建两个对象:
ObjectOne = Test()
ObjectTwo = Test()
在ChangeDictionary方法调用之前和之后打印它们的字典:
# Print values before method call
print(ObjectOne.TestDict)
print(ObjectTwo.TestDict)
# Call method
ObjectTwo.ChangeDictionary()
# Print values after method call
print(ObjectOne.TestDict)
print(ObjectTwo.TestDict)
我得到这样的输出:
{'TestKey': 'OldValue'}
{'TestKey': 'OldValue'}
* * Method call * *
{'TestKey': 'NewValue'}
{'TestKey': 'NewValue'}
所以从第二个对象调用的方法ChangeDictionary也在第一个对象中改变了值。
是Python语言错误还是其他地方的原因?
更新:如果类变量将是任何其他类型(例如-字符串)-在第一个对象变量将具有旧值:
class Test:
TestString = "OldValue"
def ChangeString(self):
self.TestString = "OldValue"
如上所述:
- init之外的元素方法是静态元素; init内部的元素方法是对象(self)的元素;他们不属于该类。
要修复此行为,请执行-
class Test:
def __init__(self): #<-------
self.TestDict = {"TestKey": "OldValue"} #<-------
def ChangeDictionary(self):
self.TestDict["TestKey"] = "NewValue"
ObjectOne = Test()
ObjectTwo = Test()
# Print values before method call
print(ObjectOne.TestDict)
print(ObjectTwo.TestDict)
# Call method
ObjectTwo.ChangeDictionary()
print("** Method call **")
# Print values after method call
print(ObjectOne.TestDict)
print(ObjectTwo.TestDict)
{'TestKey': 'OldValue'}
{'TestKey': 'OldValue'}
** Method call **
{'TestKey': 'OldValue'}
{'TestKey': 'NewValue'}
编辑:正如@juanpa所提到的。Arrivillaga,你对类函数所做的修改定义了一个不可变对象,与你之前的不可变对象分开。
注意下面两种方法的不同-
#### ORIGINAL STRING ####
class Test:
TestString = "OldValue"
def ChangeString(self):
self.TestString = "NewValue"
ObjectOne = Test()
ObjectTwo = Test()
# Print values before method call
print(ObjectOne.TestString)
print(ObjectTwo.TestString)
# Call method
ObjectTwo.ChangeString()
print("** Method call **")
# Print values after method call
print(ObjectOne.TestString)
print(ObjectTwo.TestString)
print("** Self dicts **")
print(ObjectOne.__dict__)
print(ObjectTwo.__dict__)
OldValue
OldValue
** Method call **
OldValue
NewValue
** Self dicts **
{}
{'TestString': 'NewValue'}
AND,与__init__
### FIXED STRING ###
class Test:
def __init__(self):
self.TestString = 'OldValue'
def ChangeString(self):
self.TestString = "NewValue"
ObjectOne = Test()
ObjectTwo = Test()
# Print values before method call
print(ObjectOne.TestString)
print(ObjectTwo.TestString)
# Call method
ObjectTwo.ChangeString()
print("** Method call **")
# Print values after method call
print(ObjectOne.TestString)
print(ObjectTwo.TestString)
print("** Self dicts **")
print(ObjectOne.__dict__)
print(ObjectTwo.__dict__)
OldValue
OldValue
** Method call **
OldValue
NewValue
** Self dicts **
{'TestString': 'OldValue'}
{'TestString': 'NewValue'}