2011-02-08 26 views
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類不會有同樣的問題,同時,他們所有的字典,當一個字典被修改,修改了車隊的對象。

所以這讓我更加困惑。

回答

4

您已創建shipNamesandNumber作爲類屬性,因爲它直接包含在類中。即使通過self,每個突變都會突變相同的字典。如果要避免這種情況,那麼你必須在__init__()創建實例屬性,通常是:

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

@Ignacia哦好的,謝謝!這解決了它!我很感激你的幫助。 – ChickenFur 2011-02-08 05:52:04

相關問題