1
我有一个包含字典的类。为类变量赋值是为该对象的所有实例指定它
我创建了n个类的实例。
当I + =该字典中某个键的值时,它反映在我已从该对象实例化的每个单个对象中。
如何使该字典对于该类的每个实例都是唯一的?
这里是我创建的对象:
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类不会有同样的问题,同时,他们所有的字典,当一个字典被修改,修改了车队的对象。
所以这让我更加困惑。
@Ignacia哦好的,谢谢!这解决了它!我很感激你的帮助。 – ChickenFur 2011-02-08 05:52:04