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

前端 未结 4 798
灰色年华
灰色年华 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 08:00

    It is actually possible to assign to self.__class__ in Python, but you really have to know what you're doing. The two classes have to be compatible in some ways (both are user-defined classes, both are either old-style or new-style, and I'm not sure about the use of __slots__). Also, if you do pawn.__class__ = Queen, the pawn object will not have been constructed by the Queen constructor, so expected instance attributes might not be there etc.

    An alternative would be a sort of copy constructor like this:

    class ChessPiece(object):
      @classmethod
      def from_other_piece(cls, other_piece):
        return cls(other_piece.x, other_piece.y)
    

    Edit: See also Assigning to an instance's __class__ attribute in Python

提交回复
热议问题