Python中的奇怪错误 - 变量被视为全局而非本地

时间:2015-04-13 23:15:52

标签: python class debugging variables dictionary

我正在编写一个应该模拟由一排正方形组成的游戏板的程序。在每个方格上,玩家滚动一个可以上升1,2或3的3面模具。根据滚动,玩家向前移动许多空间。为了模拟这个,每个方块链接到另外3个方块:前面的那个,下一个和之后的那个。例如......

square 1: 
roll 1 -> square 2 ... 
roll 2 -> square 3 ...
roll 3 -> square 4

问题是,每当我设置一个方块的链接时,它也会设置所有方块的链接。换句话说,程序就好像链接列表是全局变量而不是类变量。我完全对此感到困惑。

当我打印出结果时,这就是我的期望:

Square 1: 1 -> 2 ... 2 -> 3 ... 3 -> 4 
Square 2: 1 -> 3 ... 2 -> 4 ... 3 -> 5 
Square 3: 1 -> 4 ... 2 -> 5 ... 3 -> 6 

但相反,这就是我得到的:

Square 1: 1 -> 2 ... 2 -> 3 ... 3 -> 4 
Square 2: 1 -> 2 ... 2 -> 3 ... 3 -> 4 
Square 3: 1 -> 2 ... 2 -> 3 ... 3 -> 4 

以下是总代码:

class Square:
    links = {}
    number = -1

    def __init__(self, num):
        self.number = num 

    def addLink(self, destination, distance):
        if(distance < 0 or distance > 3):
            print("ERROR: invalid distance " + str(distance) + " being linked from Square " + str(self.number) + " to " + str(destination.number))
            return;
        while(destination.hasJump()):
            destination = destination.getJumpDest()
        self.links[distance] = destination

    def getLink(self, n):
        return self.links[n]

    def hasJump(self):
        return 0 in self.links 

    def getJumpDest(self):
        return self.links[0]

    def printSummary(self):
        if(self.hasJump()):
            print("Square " + str(self.number) + ": 0 -> " + str(self.getJumpDest().number))
        else:
            print("Square " + str(self.number) + ":")
            if(1 in self.links):
                  print("1 -> " + str(self.getLink(1).number))
            if(2 in self.links):
                  print("2 -> " + str(self.getLink(2).number))
            if(3 in self.links):
                  print("3 -> " + str(self.getLink(3).number))

class Board:
    squares = {}
    size = 0

    def __init__(self, boardSize = 5):
        self.size = boardSize
        for n in range(boardSize, 0, -1):
            thisSquare = Square(n); 
            if(n < boardSize-1):            
               thisSquare.addLink(self.squares[(n+1)], 1)
            if(n < boardSize-2):
               thisSquare.addLink(self.squares[(n+2)], 2)
            if(n < boardSize-3):
               thisSquare.addLink(self.squares[(n+3)], 3)
            self.squares[n] = thisSquare

    def createJump(start, finish):
        self.squares[start].addLink(self.squares[finish],True)

game = Board()
for n in range(1,5):
    game.squares[n].printSummary()

我一直在研究这个bug大约一个半小时,我得出的结论是,我要么缺少一些明显的东西,要么我对Python中的类变量有所了解。我非常感谢任何帮助。

非常感谢你!

1 个答案:

答案 0 :(得分:3)

links似乎是一个类变量,而不是一个实例变量。您可以通过在__init__()中初始化它来解决这个问题:

def __init__(self, num):
    self.number = num
    self.links = {}