为类变量分配一个值,为该对象的所有实例提供一个值 [英] Assign a value to class variable is assiging it for all instances of that object

查看:175
本文介绍了为类变量分配一个值,为该对象的所有实例提供一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字典的课程。



我创建了n个课程的数量。



当I + =该词典中的键值时,它反映在我从该对象中实例化的每个单个对象中。



如何使该字典对每个实例化都是唯一的这个类别的价格是多少?



这是我如何创建对象:

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

这是如何调用addShip方法。我有一个for循环,并验证了currentPlayer int每次递增。

  listOfPlayerFleets [currentPlayer] .addShip typeOfShip,num)

下面是我的舰队对象中的代码示例。

  class Fleet:
存储舰队编号,代表车队


shipNamesandNumber = {}


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

在pydev中,当我通过此函数调用时,shipNamesandNumbers中的每个对象都被numToAdd递增。



即使这些Fleet对象在内存中的不同位置也会发生。



我必须通过另一个类的字典?我写了一个测试类来验证这一点:

  class Foo:
使用字典测试类

myDictionary = {}

def __init __(self):
self.myDictionary = {'first':0,'second':0}

def addItem(self,key,numToAdd):
self.myDictionary [key] + = numToAdd

numOfFoos = 2
listOfFoos = []

范围内的num(0,numOfFoos):
listOfFoos.append(Foo())


listOfFoos [0] .addItem ',1)
listOfFoos [0] .addItem('first',2)
listOfFoos [1] .addItem('first',2)
print这是foo1的值它应该是3
打印列表OfFoos [0] .myDictionary

打印这是foo2的值应该是2
打印listOfFoos [1] .myDictionary

Foo类没有相同的问题,我的车队对象修改了所有的字典,当一个字典是修改了。



所以这已经使我更加困惑。

解决方案

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

  class Fleet:
def __init __(self):
self.shipNamesandNumber = {}
pre>

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.

解决方案

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

这篇关于为类变量分配一个值,为该对象的所有实例提供一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆