Can I dynamically convert an instance of one class to another?

前端 未结 4 782
灰色年华
灰色年华 2020-12-03 07:37

I have a class that describe chess pieces. I make for all type piece in the Board a class for example Pawn, Queen, keen, etc... I have a trouble in Pawn class I want to conv

4条回答
  •  自闭症患者
    2020-12-03 07:41

    One way to solve this is to have a generic Piece class and another Strategy or Characteristics class. The piece provides generic interface common to all pieces (like move_to, or something) and Strategy decides if it's possible and how to execute the command. When you want to change a pawn to a queen, you change the strategy of the piece.

    Edit: In your case it might not even be necessary to make it that complicated. You could have something like this:

    class Piece:
        def __init__(self, movefunc):
            self.move = movefunc
    
    def move_pawn(inst, unit=1):
        pass
    
    pawn = Piece(move_pawn)
    

提交回复
热议问题