构造函数中所有相同类型的不同对象的变量都引用同一个对象

时间:2013-03-03 17:44:59

标签: python list object constructor instantiation

这是我第一次在这里发帖,而且我是Python新手,所以如果我出错了,请耐心等待!我已经看到了类似的问题,但看不出明确的解决方案。这必须有一个简单的解决方案,但它让我整天感到沮丧。

我正在尝试在构造函数中创建类“Slot”的多个对象 班级“董事会”。在制作每个对象之后,我将它附加到列表中。 最后,我将遍历列表中的每个对象并调用'getHandles'方法,这应该是 输出他们独特的结果。而是显示最后一个插槽对象的结果。

Board类构造函数:

class Board:
slots = []

def __init__(self):
    slot1 = Slot(1); self.slots.append(slot1);
    slot2 = Slot(2); self.slots.append(slot2);
    slot3 = Slot(3); self.slots.append(slot3);
    slot4 = Slot(4); self.slots.append(slot4);
    slot5 = Slot(5); self.slots.append(slot5);
    slot6 = Slot(6); self.slots.append(slot6);
    slot7 = Slot(7); self.slots.append(slot7);
    slot8 = Slot(8); self.slots.append(slot8);
    slot9 = Slot(9); self.slots.append(slot9);

    print("\nprinting slot objects in list 'slot'\n");
    counter = 0;
    while counter < len(self.slots):
        print("slot number :"+str(self.slots[counter].getPosition()));
        print("slot value :"+str(self.slots[counter].getHandles()));
        counter +=1;

插槽类构造函数:

    #Slot class constructor
def __init__(self,n):
    self.setPosition(n);
    positions = coords.getLargeGridPosition(n);
    self.U[2] = positions[1]; self.D[2] = positions[2];
    self.L[2] = positions[3]; self.R[2] = positions[4];

    print("made slot object : "+str(self.getPosition()));
    print("handle values: ");
    self.getHandles();
    print(" - ");

def getHandles(self):
    print(" U:"+str(self.U)+" D:"+str(self.D)+" L:"+str(self.L)+" R:"+str(self.R));

这是我制作'Board'对象时得到的结果:

第一部分输出(在Board构造函数中创建插槽和附加):

>>> b = Board()
made slot object : 1
handle values: 
U:[1, 2, 2] D:[2, 1, 20] L:[3, 4, 10] R:[4, 3, 12]
- 
made slot object : 2
handle values: 
U:[1, 2, 5] D:[2, 1, 23] L:[3, 4, 13] R:[4, 3, 15]
- 
made slot object : 3
handle values: 
U:[1, 2, 8] D:[2, 1, 26] L:[3, 4, 16] R:[4, 3, 18]
- 
made slot object : 4
handle values: 
U:[1, 2, 29] D:[2, 1, 47] L:[3, 4, 37] R:[4, 3, 39]
- 
所有九个对象的

等等。 第二部分输出(为列表中的每个对象调用getHandle方法):

printing slot objects in list 'slot'

slot number :1
U:[1, 2, 62] D:[2, 1, 80] L:[3, 4, 70] R:[4, 3, 72]
slot value :None
slot number :2
U:[1, 2, 62] D:[2, 1, 80] L:[3, 4, 70] R:[4, 3, 72]
slot value :None
slot number :3
U:[1, 2, 62] D:[2, 1, 80] L:[3, 4, 70] R:[4, 3, 72]
slot value :None
slot number :4
U:[1, 2, 62] D:[2, 1, 80] L:[3, 4, 70] R:[4, 3, 72]
slot value :None
slot number :5
U:[1, 2, 62] D:[2, 1, 80] L:[3, 4, 70] R:[4, 3, 72]
对于附加到列表的所有9个对象,

等等。如何使变量slot1 / slot2 是指个别物品?

我已经尝试将board对象传递给slot构造函数,并使slot构造函数将'self'传递回Board对象。仍然为所有人输出单个对象的结果。 我很感激任何帮助。谢谢。

[编辑]文件的完整代码:希望缩进正确

import coords;

#store  hanndle position values

class Slot: #slot class<------------------------------------------------

    U = [1,2,"gridPosition"] #1 up
    D = [2,1,"gridPosition"] #2 down
    L = [3,4,"gridPosition"] #3 left
    R = [4,3,"gridPosition"] #4 right
    handles = [U,D,L,R] #handles 0/1/2/3

    tileValue = 0; #value 0 - 8
    tilePosition = 0; #slot 1 - 9
    overallStrain = 0; # |0-->+

    #Slot class constructor
    def __init__(self,n):
        self.setPosition(n);
        positions = coords.getLargeGridPosition(n);
        self.U[2] = positions[1]; self.D[2] = positions[2];
        self.L[2] = positions[3]; self.R[2] = positions[4];

        print("made slot object : "+str(self.getPosition()));
        print("handle values: ");
        self.getHandles();
        print(" - ");

    def getHandles(self):
        print(" U:"+str(self.U)+" D:"+str(self.D)+" L:"+str(self.L)+" R:"+str(self.R));

    #set/get position of slot(1-9)
    def setPosition(self,position):
        self.tilePosition = position;
    def getPosition(self):
        return self.tilePosition;

    #set/get tile value
    def setTileValue(self,value):
        self.TileValue = value;
    def getTileValue(self):
        return self.TileValue;

    #get handle(n) position value
    def getHandle(self,number):
        return self.handles[number]

    #get overall strain of tile
    def getTotalStrain(self):
        return self.totalStrain;
    #calculate total strain from strains of handles
    #def calculateOverallStrain(self):#<---------------
        #for handle in handles:
            #if


    #get linked tile,



class Board: #Boardclass<------------------------------------------------
    slots = []

    def __init__(self):
        slot1 = Slot(1); self.slots.append(slot1);
        slot2 = Slot(2); self.slots.append(slot2);
        slot3 = Slot(3); self.slots.append(slot3);
        slot4 = Slot(4); self.slots.append(slot4);
        slot5 = Slot(5); self.slots.append(slot5);
        slot6 = Slot(6); self.slots.append(slot6);
        slot7 = Slot(7); self.slots.append(slot7);
        slot8 = Slot(8); self.slots.append(slot8);
        slot9 = Slot(9); self.slots.append(slot9);

        print("\nprinting slot objects in list 'slot'\n");
        counter = 0;
        while counter < len(self.slots):
            print("slot number :"+str(self.slots[counter].getPosition()));
            print("slot value :"+str(self.slots[counter].getHandles()));
            counter +=1;


    #set tiles
    def setTiles(self,state):
        counter = 0;
        for slot in self.slots:
            slot.setTileValue(state[counter]);
            counter +=1;


    def getStrain(self,slot):
        tileValue = self.slots[slot].getTileValue();
        print("tile value:"+str(tileValue));
        print("handles:");
        self.slots[slot].getHandles();

        if tileValue != 0:
            linkedTiles = coords.getLinked(tileValue);
            print(str(linkedTiles));

            counter = 0;
            for l in linkedTiles:#for each linked tile
                if l != 0: #if not empty link

                    linkedTileSlot = [];#slot linked tile is set in

                    for slot in self.slots:
                        linkedTileValue = slot.getTileValue();
                        print(str(linkedTileValue));
                        if l == linkedTileValue:#found slot with linked tile
                            print("yes");
                            linkedTileSlot = slot; break;

                    ownHandle = slot.getHandle(counter);
                    print("own handle : "+str(ownHandle));
                    linkingHandle = linkedTileSlot.getHandle(ownHandle[1]-1);
                    print("linking handle : "+str(linkingHandle));
                    positions = [ownHandle[2],linkingHandle[2]]
                    print(str(positions));

                counter += 1;

1 个答案:

答案 0 :(得分:0)

正如Pavel在评论中所说,在类级别定义的任何东西都是一个类变量,在所有实例之间共享。您需要在__init__中定义这些变量,方法是将它们分配给self

class Slot: #slot class<------------------------------------------------
  def __init__(self,n):    
    self.U = [1,2,"gridPosition"] #1 up
    self.D = [2,1,"gridPosition"] #2 down
    self.L = [3,4,"gridPosition"] #3 left
    self.R = [4,3,"gridPosition"] #4 right
    self.handles = [U,D,L,R] #handles 0/1/2/3

    self.tileValue = 0; #value 0 - 8
    self.tilePosition = 0; #slot 1 - 9
    self.overallStrain = 0; # |0-->+

你也应该知道,这里有很多极其单一的Python例子。例如,整个Board init应该只是:

def __init__(self):
    self.slots = [Slot(i+1) for i in range(10)]

    print("\nprinting slot objects in list 'slot'\n");
    for slot in self.slots:
        print("slot number :%s" % slot.getPosition());
        print("slot value :%d" slot.getHandles());

此外,除非有一个很好的理由,否则我们不鼓励定义getter和setter,因为你只是访问变量,所以你不会在这里。您应该分配并返回self.position等等。