我有一个带字典的课。
我创建了该类的 n 个实例。
当我 += 该字典中某个键上的值时,它会反映在我从该对象实例化的每个对象中。
如何使该字典对于该类的每个实例都是唯一的?
这是我创建对象的方法:
for num in range(0, numOfPlayers):
listOfPlayerFleets.append(fleet.Fleet())
以下是如何调用 addShip 方法。我将其放在 for 循环中,并验证了 currentPlayer int 每次都会递增。
listOfPlayerFleets[currentPlayer].addShip(typeOfShip, num)
以下是我的舰队对象中的示例代码。
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip(self, type, numToAdd):
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
在 pydev 中,当我单步执行此函数调用时,每个具有 shipNamesandNumbers 的对象都会按 numToAdd 递增。
即使 Fleet 对象位于内存中的不同位置,也会发生这种情况。
我必须传递另一个班级的字典吗?我写了一个测试类只是为了验证这一点:
class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__(self):
self.myDictionary = {'first':0, 'second':0}
def addItem(self, key, numToAdd):
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range(0, numOfFoos):
listOfFoos.append(Foo())
listOfFoos[0].addItem('first', 1)
listOfFoos[0].addItem('first', 2)
listOfFoos[1].addItem('first', 2)
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
Foo 类不存在与我的舰队对象相同的问题,当修改一个字典时,所有字典都会被修改。
所以这让我更加困惑。