开发者

Assign a value to class variable is assiging it for all instances of that object

I have a class with a dictionary.

I create n number instances of the class.

When I += values on a key in that dictionary it is reflected in every single object I have instantiated from that object.

How do I make that dictionary unique to every instantiation of that class?

Here is how I create the Object:

for num in range(0, numOfPlayers):
    listOfPlayerFleets.append(fleet.Fleet())

Here is how call the addShip Method. I have this in a for loop and have verified that the currentPlayer int is incrementing each time.

listOfPlayerFleets[currentPlayer].addShip(typeOfShip, num)

Here is the code in my fleet object below for the example.

class Fleet:
""" Stores Fleet Numbers, Represents a fleet """


   shipNamesandNumber = {}


   def addShip(self, type, numToAdd):
      self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd  

In pydev when I step through this function call every object with shipNamesandNumbers is incremented by the numToAdd.

This happens even those the Fleet objects are at different locations in memory.

Do I have to pass in a dictionary from another class? I wrote a test class just to verify this:

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

The Foo class doesn't have the same problem as my fleet objects having all their dictionaries modified when one dictionary is modified.

开发者_JS百科

So this has made me even more confused.


You've created shipNamesandNumber as a class attribute since it's contained directly within the class. Each mutation, even via self, mutates the same dictionary. If you want to prevent this then you must create an instance attribute, usually in __init__():

class Fleet:
  def __init__(self):
    self.shipNamesandNumber = {}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜