【发布时间】:2011-02-08 05:39:02
【问题描述】:
我有一堂带字典的课。
我创建了 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 类与我的舰队对象没有相同的问题,当一个字典被修改时,它们的所有字典都被修改了。
所以这让我更加困惑。
【问题讨论】:
标签: python object dictionary global