Python repr&将类实例作为参数传递

时间:2013-12-01 16:51:51

标签: python dictionary key repr keyerror

所以我有一个课程,我设置了类似

的课程
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()

1 个答案:

答案 0 :(得分:1)

错误很明显 - self.game.aJouer不包括self.selection中的作品作为关键字。

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

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

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