为类变量赋值是为该对象的所有实例分配它

发布于 2024-10-16 08:17:10 字数 1490 浏览 6 评论 0原文

我有一个带字典的课。

我创建了该类的 n 个实例。

当我 += 该字典中某个键上的值时,它会反映在我从该对象实例化的每个对象中。

如何使该字典对于该类的每个实例都是唯一的?

以下是我创建对象的方法:

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 类没有与我的舰队对象在修改一个字典时修改所有字典的问题相同的问题。

所以这让我更加困惑。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落叶缤纷 2024-10-23 08:17:10

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

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

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 = {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文