1

所以我有一门课,我设置了类似的东西

class Piece: 
    def __init__(): 
        self.txt = "\u2665"

    # some methods...
    # including a method validMovements(), which works properly, no errors here

    def __repr__():
        return self.txt

现在我继续执行以下代码

class GameManagement: 
    # various methods, no errors here

    def calculatePossibleMoves() # this is called at the end of each turn, for the next turn, this is also calculated in the initialization function of the GameManagement class, the problem is not here
        self.possibleMoves = {}
        for piece in self.piecesDict:  # contains all pieces
            self.possibleMoves[piece] = piece.validMovements()

然后,在另一个类中,我使用了这个变量

# note that self.selection contains an instance of the Piece class object
# and self.game contaisn a GameManaement class object
l = self.game.possibleMoves[self.selection]
# i get my error here, it seems liek in the GameManagement class, the dict uses the calss instance as key, however her it uses __repr__ as the key, instead of the object

有没有办法解决这个问题(阅读评论中的详细信息)?

回溯如下:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "C:\Users\Saume\Workspace\ChessUI\src\ui\gameboard.py", line 189, in select
    self.move(event) # call move
  File "C:\Users\Saume\Workspace\ChessUI\src\ui\gameboard.py", line 205, in move
    self.draw()
  File "C:\Users\Saume\Workspace\ChessUI\src\ui\gameboard.py", line 142, in draw
    self.createcanvas()
  File "C:\Users\Saume\Workspace\ChessUI\src\ui\gameboard.py", line 120, in createcanvas
    l = self.game.aJouer[self.selection]
KeyError: ♙

请注意,我在回溯中的一些代码是法语的,但它正是我把它放在那里的方式。

def select(self, event):
        """Selectionne une piece"""
        if self.selection == None: # il n'y a pas de selection
            try: 
                # coordonnees
                x = event.x // self.size
                y = event.y // self.size
                # piece
                p = self.game.board.getPiece(y, x)
                if p != None: 
                    if p.color == (self.game.time + 1) % 2: # piece de couleur alliee au joueur actuel 
                        self.selection = p
                    else: # piece ennemie
                        raise err.InvalidSelection("La piece selectionnee n'est pas de votre couleur.")
                else: 
                    raise err.EmptySelection("Il n'y a aucune piece sur la case selectionnee.")

            except err.InvalidSelection as e: 
                self.errorLabel.config(text=e) # afficher le message d'erreur
            except err.EmptySelection as e: 
                self.errorLabel.config(text=e) # afficher le message d'erreur
        else: # il y a deja une piece selectionnee
            self.move(event) # call move
        self.draw()
4

1 回答 1

1

错误很清楚 -self.game.aJouer不包括,作为关键,在self.selection.

请注意,您没有显示任何保证这一点的代码。实际上,您根本没有显示任何显示aJouer的代码。

结果不用__repr__作键。你被错误信息误导了。当 python 想要显示一个实例时(例如当它报告错误时),它调用. 这就是那里正在发生的一切。与实际实例之间没有混淆。__repr____repr__

实际上,用作键的是返回的值__hash__(与__equals__中的哈希算法一起使用dict)。但是如果您没有替换它,那么默认版本应该可以正常工作。

于 2013-12-01T21:41:26.417 回答