【问题标题】:Assign a value to class variable is assiging it for all instances of that object为类变量赋值是为该对象的所有实例赋值
【发布时间】: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


    【解决方案1】:

    您已将shipNamesandNumber 创建为类属性,因为它直接包含在类中。每个突变,甚至是通过self,都会改变同一个字典。如果你想防止这种情况发生,那么你必须创建一个实例属性,通常在__init__():

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

    【讨论】:

    • @Ignacia 哦,好的,谢谢!那解决了它!非常感谢您的帮助。
    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多