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

丶灬走出姿态 提交于 2019-12-02 08:53:25

问题


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.

So this has made me even more confused.


回答1:


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 = {}


来源:https://stackoverflow.com/questions/4929969/assign-a-value-to-class-variable-is-assiging-it-for-all-instances-of-that-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!